ES6 Promise对象学习心得

来源:互联网 发布:中国统计网数据库 编辑:程序博客网 时间:2024/06/08 01:55

学习了阮一峰老师的ES6入门,在学习fetch的时候顺带复习一下promise,特此记录下自己的一些理解。

基本用法

var promise_ex = new Promise(function(resolve, reject){    //some code    if (/*判断异步操作成功的条件 */){        resolve(value);    } else {        reject(error);    }});

Promise对象一共有三种状态:pending(未完成)、resolved(成功)、rejected(失败)。上面代码中resolve()函数执行后就告诉Promise对象将状态改为成功,而reject()函数则相应地把状态改为失败,两个函数都可以传入参数给回调函数使用。

promise_ex.then(function(value){    //成功时需要执行的代码},function(error){    //失败时需要执行的代码});

then方法可以接受两个回调函数作为参数,其中第二个函数不是必需的。then方法作用相当于明确promise实例的成功回调函数和失败回调函数。所以使用Promise的思路是在new一个promise对象时做好判断(什么时候执行resolve,什么时候执行reject),然后再使用then方法分别写好成功和失败的回调函数。

执行流程

let promise = new Promise(function(resolve, reject) {  console.log('Promise');  resolve();});promise.then(function() {  console.log('Resolved.');});console.log('Hi!');// Promise// Hi!// Resolved

then方法指定的回调函数将在当前脚本所有同步任务执行完才会执行。

链式then调用

then的作用是为promise实例添加回调函数,但它返回的是一个新的promise实例(不同于原来调用它的实例)。因此可以采用链式写法。

getJSON("/posts.json").then(function(response) {  return response.data;}).then(function(data) {  // ...  console.log(data);});

上面的代码中第一个then中的回调函数完成后会把其返回结果作为参数传入第二个then中的回调函数。

getJSON("/post/1.json").then(  post => getJSON(post.commentURL)).then(  comments => console.log("Resolved: ", comments),  err => console.log("Rejected: ", err));

如果前一个回调函数返回的是一个promise对象(即有异步操作),这时后一个回调函数会等待该promise对象的状态改变后才会被调用。上面代码中getJSON(post.commentURL)返回的promise对象如果变为resolved,就会调用funcA

finally()方法

finally方法接受一个回调函数作为参数,不管promise对象的状态是什么都会执行。
下面是一个例子,服务器使用Promise处理请求,然后使用finally方法关掉服务器。

server.listen(0)  .then(function () {    // run test  })  .finally(server.stop);
0 0
原创粉丝点击