Javascript Promise技术

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

------------------越是喧嚣的世界,越需要宁静的思考------------------ 合抱之木,生于毫末;九层之台,起于垒土;千里之行,始于足下。 积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。故不积跬步,无以至千里;不积小流,无以成江海。骐骥一跃,不能十步;驽马十驾,功在不舍。锲而舍之,朽木不折;锲而不舍,金石可镂。蚓无爪牙之利,筋骨之强,上食埃土,下饮黄泉,用心一也。蟹六跪而二螯,非蛇鳝之穴无可寄托者,用心躁也。
原文地址:https://www.cnblogs.com/feng9exe/p/14686689.html