Javascript Promise技术

时间:2021-04-22 16:05:11   收藏:0   阅读:0

 

Simple explain:

In ES2018

When the catch method is called with argument onRejected, the following steps are taken:

  1. Let promise be the this value.
  2. Return ? Invoke(promise, "then", ? undefined, onRejected ?).

that means:

promise.then(f1).catch(f2)

equals

promise.then(f1).then(undefiend, f2)

http://cz2013.github.io/2015/08/27/promise/

三种状态逻辑关系如下图所示:
技术图片

THEN 和 CATCH

上面的例子已经让我们认识了.then().catch()的链式写法,其实在Promise里可以将任意个方法连在一起作为一个方法链(method chain)。下面我们增加方法链长度:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
function taskA() {
console.log("Task A");
}
 
function taskB() {
console.log("Task B");
}
 
function onRejected(error) {
console.log("Catch Error: A or B", error);
}
 
function finalTask() {
console.log("Final Task");
}
 
var promise = Promise.resolve();
promise
.then(taskA)
.then(taskB)
.catch(onRejected)
.then(finalTask);

 

上面代码中的promise chain的执行流程,如果用一张图来描述一下的话,像下面的图那样。
技术图片
我们可以这样理解:

then:注册onFulfilled时的回调函数
catch:注册onRejected时的回调函数

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!