promise-笔记

promise

 

 

封装Promise

var fs = require('fs')

function pReadFile(filePath) {
  return new Promise(function (resolve, reject) {
    fs.readFile(filePath, 'utf8', function (err, data) {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}

pReadFile('./data/a.txt')
  .then(function (data) {
    console.log(data)
    return pReadFile('./data/b.txt')
  })
  .then(function (data) {
    console.log(data)
    return pReadFile('./data/c.txt')
  })
  .then(function (data) {
    console.log(data)
  })

 

 

Promise对象是一个构造函数——https://www.cnblogs.com/lvdabao/p/es6-promise-1.html

console.dir——https://www.kancloud.cn/iplaylf2/javascript/363984

const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

 

posted @ 2018-08-01 23:57  EthanCheung  阅读(84)  评论(0编辑  收藏  举报