定时器

Promise是什么

A promise represents the eventual result of an asynchornous operation

翻译成中文,意思就是:Promise 一个异步操作的最终结果

直译过来的结果不太容易理解,可以将其理解为一个状态机制,它存在三种不同额状态,并且在某一时刻只能有一种状态。

  1. pending:表示还在执行。
  2. Fulfilled(或者resolved):执行成功。
  3. Rejected:执行失败。
  • 一个Promis是对一个操作(通常是一个异步操作)的封装,异步操作有等待完成、成功、失败三种结果,对应三种状态。
  • Promise的状态只能从Pending转换为Fulfilled或者转换为Rejected,一旦状态转换完成就无法改变。

ES2015中Promise

  1. 将异步封装成prmise

  • 要使用Promise,首先你要有一个Promise(废话),我么可以用Promise的构造函数封装一个现有的异步操作,代码如下:
1
2
3
4
5
6
7
8
var promise = new Promise(function (resoleve,reject){
//... some code
if (/*if 异步成功*/){
resolve(cvalue);
}else|{
reject(error);
}
});
  • 以读取文件内容的fs.readFile为例子,使用Promise封装的方法如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
var fs = require ("fs");
function readFile_Promise(path){
return new Promise(function (resoleve,reject){
fs.readFile(path,"UFT-8",function(err,data){
if(data){
resolve(data);
}else{
reject(err);
}
});
});
}
  • 其实只要在回调函数中针对不同的返回结果调用resolve或者reject方法即可。
  • resolve和reject方法也没做多余的操作,仅仅只是把一步的结果传递出去而已,对于一步的处理,是交给then方法来完成的。
  1. 使用then方法获取结果

  • 一个then的方法通常是如下这种形式:
1
2
3
4
5
ptomise.then(function(value){
//成功
},function(err){
//失败
});
  • then方法接收两个匿名函数作为参数,它们代表onResolved和onRejected函数。
  • value和error代表回调的结果。两者必有一个不为空。
  1. then方法的返回值

  • then的方法总是返回一个新的promise的对象,这也表示对于一个Promise,可以多次调用他的then方法,但由于promise的默认的返回是一个空对象,除非做一些额外的操作,否则这一操作通常得不到有意义的值。
1
2
3
4
5
6
var promise = readFile_promise("foo.txt");
promise.then(function (value){
console.log(log);//foo
}).then(function (value){
console.log(log);//undefind
});
  • 开发者可以在回调函定义一个新的Promise,然后使用return来返回。
1
2
3
4
5
6
7
var promise = readFile_promise("foo.txt");
promise.then(function (value){
console.log(log);//foo
return readFile_promise("foo.txt");
}).then(function (value){
console.log(log);//foo
});
  1. promise的执行

    虽然我们会通过方法来获取promise的结果,danpromise是当then方法被调用后才会执行吗?举个例子,看下列代码怎么输出?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    var promise = new promise(resolve,reject) => {
    conlose.log("begin");
    resolve();
    });
    setTime(()=>{
    promise.then(() => {
    console.log("end");
    })
    },5000);

实际上运行一下就会发现,程序立刻打印出begin,然后等待五秒,随后在打印出end。

Promise从被创建的那一刻起就开始执行,then方法只是提供了访问promise状态的接口,与Promise的执行无关。