zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Javascript Promise技术

2023-09-11 14:18:43 时间

 

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时的回调函数