Promise

js async - Promise

How Promise works is that, each async task will return result and construct a Promise instance, and each instance has a then, which is used for directing to next callback func.
Here is a simple promise example:

1
2
3
4
5
6
7
8
9
function f1(resolve, reject) {
// async codes here..
}

var p1 = new Promise(f1); // f1 is an async callback function/task,
// promise instance p1 receives f1's result

// when f1 is done, do f2
p1.then(f2); // f2 is the next async func to be executed

Promise changed the style of multiple nesting levels.
In olde way, these steps will be written as:

1
2
3
4
5
6
7
8
9
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// ...
});
});
});
});

using Promise, it will be like:

1
2
3
4
(new Promise(step1))
.then(step2)
.then(step3)
.then(step4);

Promise state

1
2
3
4
5
6
7
8
9
const promise = new Promise(function(resolve, reject) {
// ... some code

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

resolve and reject is two functions provided by JS engine. (no need to declare)

  • resolve : change the state of promise obj from pending to resolved
  • reject : change the state of promise obj from pending to rejected

note: when the state is changed, nothing can be done to roll back the transaction.

我的理解是,resolve(), reject()像两个一次性boolean函数,一旦被call就会从false变为true并直接将promise实例做上resolved/rejected的状态标记。

If the Promise instance has already been generated, can use then declare the callback functions for these two state:

1
2
3
4
5
6
7
promise.then(function(value) {
// success
// call when state changed to resolved
}, function(error) {
// failure
// call when state changed to rejected
});

Both functions receive result returned by Promise obj as paremeter value/error.

Promise 新建后会立即执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let promise = new Promise(function(resolve, reject) {
console.log('Promise'); //立即执行
resolve(); // state changed, call then
});

// `then` 要在当前脚本的所有同步任务(同级的)都执行完才会执行
promise.then(function() { // only resolve func
console.log('resolved.');
});

console.log('Hi!');

// Promise
// Hi!
// resolved

For more info : ES6入门(阮一峰) | MDN - Promise