美文网首页前端直通车
es6全家桶(三)——对象的扩展、Promise对象

es6全家桶(三)——对象的扩展、Promise对象

作者: 一个顽固的橙子 | 来源:发表于2017-07-25 10:51 被阅读19次
图片来自简书

对象的扩展

图片来自简书

Promise对象

  • 含义
    获取异步操作的消息,提供统一的API

  • 特点
    1)对象的状态不受外界影响,有三种状态:Pending(进行中)、Resolved(已完成,又称 Fulfilled)和Rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。

2)Promise对象的状态改变,只有两种可能:从Pending变为Resolved和从Pending变为Rejected。一旦状态改变,就不会再变,任何时候都可以得到这个结果

  • 基本用法
    Promise对象是一个构造函数
    第一步:创建Promise实例
var promise = new Promise(function(resolve, reject) {
  // ... some code

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

第二步:Promise实例生成以后,可以用then方法分别指定Resolved状态和Reject状态的回调函数。

promise.then(function(value) {
  // success
}, function(error) {
  // failure
});

第三步:then方法的链式调用, 用来添加状态改变时的回调函数

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

第四步:添加catch()方法,用于指定发生错误时的回调函数。

getJSON('/posts.json').then(function(posts) {
  // ...
}).catch(function(error) {
  // 处理 getJSON 和 前一个回调函数运行时发生的错误
  console.log('发生错误!', error);
});

Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个catch语句捕获。

getJSON('/post/1.json').then(function(post) {
  return getJSON(post.commentURL);
}).then(function(comments) {
  // some code
}).catch(function(error) {
  // 处理前面三个Promise产生的错误
});

一般来说,不要在then方法里面定义Reject状态的回调函数(即then的第二个参数),总是使用catch方法。

// bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });
// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });

相关文章

网友评论

    本文标题:es6全家桶(三)——对象的扩展、Promise对象

    本文链接:https://www.haomeiwen.com/subject/yxdfkxtx.html