Promise---如何用?

Promise对象

1、用法说明
  1)Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject
  2)Promise 新建后就会立即执行。
  3)Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数
    then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数。

  4)调用resolve或reject以后,Promise 的使命就完成了,后继操作应该放到then方法里面,而不应该直接写在resolve或reject的后面。所以,最好在它们前面加上return语句,这样就不会有意外。

2、Promise.prototype.then()
  Promise实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。它的作用是为 Promise 实例添加状态改变时的回调函数。
  then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法
  getJSON("/post/1.json").then(function(post) {
    return getJSON(post.commentURL);
  }).then(function funcA(comments) {
    console.log("resolved: ", comments);
  }, function funcB(err){
    console.log("rejected: ", err);
  });

3、Promise.prototype.catch()
  Promise.prototype.catch方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数。

  getJSON('/posts.json').then(function(posts) {
    // ...
  }).catch(function(error) {
    // 处理 getJSON 和 前一个回调函数运行时发生的错误
    console.log('发生错误!', error);
  });
  上面代码中,getJSON方法返回一个 Promise 对象,如果该对象状态变为resolved,则会调用then方法指定的回调函数;如果异步操作抛出错误,状态就会变为rejected,就会调用catch方法指定的回调函数,处理这个错误。另外,then方法指定的回调函数,如果运行中抛出错误,也会被catch方法捕获。

  如果 Promise 状态已经变成resolved,再抛出错误是无效的。
  const promise = new Promise(function(resolve, reject) {
    resolve('ok')
    reject(new Error('test'));
  });
  promise
    .then(function(val) {console.log(val)})
    .catch(function(error) {console.log(error)})
  上面代码中,Promise 在resolve语句后面,再抛出错误,不会被捕获,等于没有抛出。因为 Promise 的状态一旦改变,就永久保持该状态,不会再变了。

 Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个catch语句捕获。
  getJSON('/post/1.json').then(function(post) {
    return getJSON(post.commentURL);
  }).then(function(comments) {
    // some code
  }).catch(function(error) {
    // 处理前面三个Promise产生的错误
  });
  上面代码中,一共有三个 Promise 对象:一个由getJSON产生,两个由then产生。它们之中任何一个抛出的错误,都会被最后一个catch捕获。

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

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

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

  Promise 内部的错误不会影响到 Promise 外部的代码的执行
  const someAsyncThing = function() {
    return new Promise(function(resolve, reject) {
      resolve(x + 2);
    });
  };
  someAsyncThing().then(function() {
    return someAsyncThing();
  }).catch(function(err) {
      console.log('oh on',err);
      y + 2;
  }).then(function() {
    console.log('carry on');
  }).catch(function(err) {
    console.log(err);
  })

4、Promise.prototype.finally()
finally方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的。

5、Promise.all()
Promise.all方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。
 const p = Promise.all([p1, p2, p3]);
p的状态由p1、p2、p3决定,分成两种情况。

(1)只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。

(2)只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。
注意,如果作为参数的 Promise 实例,自己定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()的catch方法。

  const p1 = new Promise((resolve, reject) => {
    resolve("hello");
  })
  .then(result => console.log(result))
  .catch(e => console.log(e));

  const p2 = new Promise((resolve, reject) => {
    throw new Error('报错了')
  })
  .then(result => console.log(result))
  //.catch(e => console.log(e));

  Promise.all([p1, p2])
  .then(result => console.log(result))
  .catch(e => console.log(e));

6、Promise.race()
const p = Promise.race([p1,p2,p3])
Promise.race方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例。
只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。
const p = Promise.race([
  fetch('/resource-that-may-take-a-while'),
  new Promise(function (resolve, reject) {
    setTimeout(() => reject(new Error('request timeout')), 5000)
  })
]);

 p
  .then(console.log)
  .catch(console.error);
上面代码中,如果 5 秒之内fetch方法无法返回结果,变量p的状态就会变为rejected,从而触发catch方法指定的回调函数

7、Promise.resolve()
有时需要将现有对象转为 Promise 对象,Promise.resolve方法就起到这个作用
Promise.resolve('foo');//等价于
new Promise(resolve => resolve('foo'));

Promise.resolve方法参数四种情况
1) 参数是一个Promise的实例
如果参数是 Promise 实例,那么Promise.resolve将不做任何修改、原封不动地返回这个实例。
2)参数是一个thenable对象
thenable对象指的是具有then方法的对象
let thenable = {
  then: function(resolve, reject) {
    resolve(42);
  }
}
let p1 = Promise.resolve(thenable);
p1.then(function(value) {
  console.log(value);
})
3)参数不具有then方法的对象,或者根本就不是对象。则Promise.resolve方法返回一个新的 Promise 对象,状态为resolved。
const p = Promise.resolve('hello');
p.then(function(s) {
  console.log(s);
})

4)不带有任何参数
Promise.resolve方法允许调用时不带参数,直接返回一个resolved状态的 Promise 对象。


8、Promise.reject()
Promise.reject(reason)方法也会返回一个新的 Promise 实例,该实例的状态为rejected。
注意,Promise.reject()方法的参数,会原封不动地作为reject的理由,变成后续方法的参数。这一点与Promise.resolve方法不一致。


9 Promise.try()
事实上,Promise.try就是模拟try代码块
database.users.get({id: userId})
  .then(...)
  .catch(...)
上面代码中,database.users.get()返回一个 Promise 对象,如果抛出异步错误,可以用catch方法捕获,就像下面这样写。
但是database.users.get()可能还会抛出同步错误(比如数据库连接错误,具体要看实现方法),这时你就不得不用try...catch去捕获。
try {
  database.users.get({id: userId})
  .then(...)
  .catch(...)
} catch (e) {
// ...
}
上面这样的写法就很笨拙了,这时就可以统一用promise.catch()捕获所有同步和异步的错误。
Promise.try(database.users.get({id: userId}))
.then(...)
.catch(...)

posted @ 2018-03-14 16:14  麦芽无心  阅读(186)  评论(0编辑  收藏  举报