table of Contents
Another example returns Promise
Basic Usage
Promise object is a constructor, following example generates a target promise
Promise = const new new Promise ((Resolve, Reject) => { IF ( to true ) { Resolve ( 'asynchronous operation was successful' ); } the else { rejecte ( 'asynchronous operation failed " ); } })
Promise constructor takes a function as a parameter, this function takes two parameters, these parameters are functions
Results for the first function state successful asynchronous and asynchronous successfully pass out as a parameter, while promise changed resolved
The second function for the asynchronous failure, and the result of the asynchronous failure to pass out as a parameter, and the state is changed to promise rejected
Another example returns Promise
Typically reject function returns an error message is asynchronous, Resolve function returns a normal ideal value, and this value may also be another example Promise,
If the return is another example of Promise, then this example will determine the state of the current instance of the Promise, his natural state will fail
P1 = const new new Promise ( function (Resolve, Reject) { // ... }); const P2 = new new Promise ( function (Resolve, Reject) { // ... the setTimeout (() => {Resolve (P1) , 2000}); // P1 p2 determines the state of a state, rather than wait until 2S })
Promise.prototypeof.then
The method then function accepts two parameters, the result typically requires asynchronous Promise as a parameter into
The first function is asynchronous success (resolved) execution
The first function is asynchronous failure (resolved) executed (can not transmit the function, use asynchronous listener method catch failure)
promise.then((res)=>{ console.log(res); }, (rej)=>{ cnosole.log(rej); })
The new method will then Promise objects, so you can chain calls. If there is a return value, the return value will be passed to the new object as a parameter Promise
promise.then((res)=>{ console.log(res); return 'newPromise'; }, (rej)=>{ cnosole.log(rej); }).then((res => { console.log(res); })
If the new promise returned object exists asynchronous operation, such as returning a new instance of the object Promise, then we will wait until the latter method executed when the state changes promise
Promise.prototype.catch
Mentioned above, then there are two functions of a method of receiving parameters, which are executed when successes and failures, and the failure of the function recommended method of use catch
The method then catch may fulfill the functions of the second parameter, but it can be intuitively with the codes
let a = 1; let promise = new Promise(function(resolve, reject){ if(a==10){ resolve('成功'); }else{ reject('失败'); } }); promise.then(res=>{ console.log(res); }).catch(err=>{ console.log(err); })
Error promise object a "bubble" in nature, it will always back pass, until it is captured so far. In other words, the error will always be the next catch
statement capture.
Promise.prototype.finally()
finally, regardless of the method used to target Promise final state, the operation will be performed specified.
promise
.finally(() => {});
Promise.resolve()
Convert an existing object promise object points below four cases
1. If the argument is Promise instance, then promise.resolve will not do any modification, is returned unchanged this instance.
2. If the argument is a thenable object. thenable objects then refers to the object having methods, such as the following objects. Promise.resolve method converts the object into Promise object, and then immediately execute thenable
object then
methods.
let thenable = { then: function(resolve, reject) { resolve(42); } }; let p1 = Promise.resolve(thenable); p1.then(function(value) { console.log(value); // 42 });
3. If the parameter value is an original or not having an then
object method, the Promise.resolve method returns Promise a new object state resolved
. The following example of code generation of a new object Promise p
. Because the string Hello
does not belong to asynchronous operation (determination method is then subject does not have a string method), and returns from a state Promise instance is generated resolved
, the callback function is executed immediately. Promise.resolve
Method parameters, simultaneously passed to the callback function.
const p = Promise.resolve('Hello'); p.then(function (s){ console.log(s) }); // Hello
4. Promise the object with no parameters Promise.resolve method allows the caller directly return a resolved state. It should be noted, resolve immediately () the Promise object is executed when at the end of the current round of "event loop" (event loop), rather than when the next round start "event loop" .
the setTimeout ( function () { the console.log ( 'Three' ); }, 0 ); // start execution at an "event loop", . Promise.resolve () the then ( function () { the console.log ( ' TWO ' ); }); // executed when the current round of "event loop" end console.log ( ' One ' ); // One // TWO // Three
Promsie.reject ()
Also a promise to convert an existing object into an object, but the promise of the state of the object is rejected
const p = Promise.reject ( 'wrong');
Promise of execution order
Promise constructor itself is performed synchronously
The method will then be placed in a micro task (Microtask) queue
setTimeout timer into the macro task (macrotask) queue
When the synchronization task executed, the task queue task micro sequentially into the main thread of execution, when a task queue is empty after the micro-macro task queue sequentially into the main task execution
setTimeout(() => { console.log(0); },0) new Promise(resolve => { resolve(1); Promise.resolve().then(t => { console.log(2); }) console.log(3); }).then(t => { console.log(t); }) console.log(4); // 3 // 4 // 2 // 1 // 0
现在分析上面的代码
1. 遇到定时器,将它放到宏任务队列中(这是第一个宏任务)
2. 同步执行构造函数
3. 在构造函数中遇到一个 then 方法,将他放到微任务队列中(这是第一个微任务)
4. console.log(3) 执行,打印出 3
5. 遇到第二个 then 方法,将他放到微任务队列的末尾
6. console.log(4) 执行,打印出 4
7. 读取微任务队列中的任务,依次打印出 2 1
8. 读取宏任务队列中的任务,打印出 0