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 | function f1(resolve, reject) { |
Promise changed the style of multiple nesting levels.
In olde way, these steps will be written as:
1 | step1(function (value1) { |
using Promise, it will be like:
1 | (new Promise(step1)) |
Promise state
1 | const promise = new Promise(function(resolve, reject) { |
resolve
and reject
is two functions provided by JS engine. (no need to declare)
resolve
: change the state of promise obj from pending to resolvedreject
: 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 | promise.then(function(value) { |
Both functions receive result returned by Promise obj as paremeter value
/error
.
Promise 新建后会立即执行
1 | let promise = new Promise(function(resolve, reject) { |
For more info : ES6入门(阮一峰) | MDN - Promise