Node.js knowledge system (7)-Promise of asynchronous programming

Node.js knowledge system (7)-Promise of asynchronous programming

This is the text I was involved in more challenging twenty-seven days, the event details see: more text challenge

What is Promise

Promise is a solution for asynchronous programming!

  • Results that are not available in the current event loop, but future event loops will give you results
  • Is a state machine
    • pengding
    • resolved
    • reejectd

Look at the state flow from the code

Transfer test from pending to resolve

( function () { const res = new Promise ( ( resolve, reject ) => { setTimeout ( () => { resolve(); }, 500 ); }); console .log( "500ms" , res); setTimeout ( () => { console .log( "800ms" , res); }, 800 ); })(); Copy code

Print out the following

The result is in line with our expectations

  • We can't get it right away
    promise
    The result at this time
    promise
    In
    pending
    status
  • You must wait for a period of time to get it
    promise
    The result at this time
    promise
    In
    fulfilled
    status

Transfer test from pending to reject

( function () { const res = new Promise ( ( resolve, reject ) => { setTimeout ( () => { reject( new Error ( "error" )); }, 500 ); }); console .log( "500ms" , res); setTimeout ( () => { console .log( "800ms" , res); }, 800 ); })(); Copy code

Print out the following

The result is in line with our expectations

  • We can't get it right away
    promise
    The result at this time
    promise
    In
    pending
    status
  • You must wait for a period of time to get it
    promise
    The result at this time
    promise
    In
    reject
    status

Note: if

pengding
State into
reject
Status, if this error is not captured correctly, the error will be thrown to the JS global

The reslove state flow goes to the reject state test

( function () { const res = new Promise ( ( resolve, reject ) => { setTimeout ( () => { resolve(); }, 300 ); setTimeout ( () => { reject( new Error ( "error" )); }, 500 ); }); console .log( "500ms" , res); setTimeout ( () => { console .log( "800ms" , res); }, 800 ); })(); Copy code

Print out the following

It can be found!

At 300ms

promise
'S status has been switched to
resolve
, Will never reach after switching
reject
status

  • pending
    Can only flow to
    resolve
    or
    reject
    ;
  • resolve
    with
    reject
    Can't circulate with each other;

Use then, catch to capture the result of the promise

( function () { const res = new Promise ( ( resolve, reject ) => { setTimeout ( () => { resolve( 3 ); }, 300 ); }) .then( ( result ) => { console .log( "result" , result); }) .catch( ( error ) => { console .log( "error" , error); }); console .log( "300ms" , res); setTimeout ( () => { console .log( "800ms" , res); }, 800 ); })(); Copy code

Print out the following

It can be found

  • then
    Yes
    promise
    The state flow goes to
    reslove
    State can get the result

( function () { const res = new Promise ( ( resolve, reject ) => { setTimeout ( () => { reject( new Error ( "error-3" )); }, 300 ); }) .then( ( result ) => { console .log( "result" , result); }) .catch( ( error ) => { console .log( "error" , error); }); console .log( "300ms" , res); setTimeout ( () => { console .log( "800ms" , res); }, 800 ); })(); Copy code

Print out the following

It can be found

catch
Yes
promise
The state flow goes to
reject
The result can be obtained by the state, and the previous global JS error can already be
catch
Caught

.then .catch summary

  • resolved
    The state of the Promise will call back the first one afterwards
    .then
  • rejected
    The state of the Promise will call back the first one afterwards
    .catch
  • anyone
    rejected
    There is no behind the state cut
    .catch
    Promise will cause a global error in the Js environment

Promise is superior to callback

Solve the problem of asynchronous process control-callback hell

Let's continue the previous interview example

Use Promise to transform the previous interview function

function interview () { return new Promise ( function ( resolve, reject ) { setTimeout ( () => { if ( Math .random()> 0.4 ) { //resolve, reject can only accept one parameter resolve( "success" ); } else { reject( new Error ( "fail" )); } }, 1000 ); }); } ( function () { const res = interview(); res .then( ( result ) => { console .log( "The interview was successful! I laughed" ); }) .catch( ( error ) => { console .log( "Interview failed! I cried" ); }); })(); Copy code

Test for the case where an error is thrown in .then

function interview () { return new Promise ( function ( resolve, reject ) { setTimeout ( () => { if ( Math .random()> 0.4 ) { //resolve, reject can only accept one parameter resolve("success" ); } else { reject( new Error ( "fail" )); } }, 500 ); }); } ( function () { const promsie1 = interview(); const promsie2 = promsie1.then( ( result ) => { throw new Error ( "The interview was successful! I laughed, but I refused" ); }); setTimeout ( () => { console .log( "promsie1" , promsie1); console .log( "promsie2" , promsie2); }, 800 ); })(); Copy code

The above code can be seen,

**.then
Return a brand new Promise, the result state of this Promise is determined by
.then
Is determined by the result of the callback function

  • If the callback function ends up being
    throw
    , Then enter rejected
  • If the callback function ends up being
    return
    , Then enter resolved

.catch in the normal value of the test

function interview () { return new Promise ( function ( resolve, reject ) { setTimeout ( () => { if ( Math .random()> 0 ) { //resolve, reject can only accept one parameter resolve( "success" ); } else { reject( new Error ( "fail" )); } }, 500 ); }); } ( function () { const promsie1 = interview(); const promsie2 = promsie1.catch( ( result ) => { return "Although the interview failed, I still laughed" ; }); setTimeout ( () => { console .log( "promsie1" , promsie1); console .log( "promsie2" , promsie2); }, 800 ); })(); Copy code

.catch
Return a brand new Promise, the result state of this Promise is determined by
.catch
Is determined by the result of the callback function

  • If the callback function ends up being
    throw
    , Then enter rejected
  • If the callback function ends up being
    return
    , Then enter resolved

.catch, .then and then return Promise

function interview () { return new Promise ( function ( resolve, reject ) { setTimeout ( () => { if ( Math .random()> 0.4 ) { //resolve, reject can only accept one parameter resolve( "success" ); } else { reject( new Error ( "fail" )); } }, 500 ); }); } ( function () { const promsie1 = interview(); const promsie2 = promsie1 .then( ( result ) => { return new Promise ( function ( resolve, reject ) { setTimeout ( () => { resolve( "The interview was successful!, give me 400ms to summarize" ); }, 400 ); }); }) .catch( ( result ) => { return new Promise ( function ( resolve, reject ) { setTimeout ( () => { resolve( "Interview failed, give me 400ms to summarize" ); }, 400 ); }); }); setTimeout ( () => { console .log( "800ms promsie1" , promsie1); console .log( "800ms promsie2" , promsie2); }, 800 ); setTimeout ( () => { console .log( "1000ms promsie1" , promsie1); console .log( "1000ms promsie2" , promsie2); }, 1000 ); })(); Copy code

If in

.catch
,
.then
If a Promise is returned, it will wait for the execution result of this Promise

If the callback function finally returns the Promise, the promise is consistent with the Promsie state of the callback function's return, which means that multiple asynchronous tasks can be executed serially in the chain call of the Promise!

Promise to achieve multiple rounds of interviews-serial

//round function interview ( round ) { return new Promise ( function ( resolve, reject ) { setTimeout ( () => { if ( Math .random()> 0.4 ) { //resolve, reject can only be accepted One parameter resolve( "success" ); } else { const error = new Error ( "fail" ); reject({ round, error }); } }, 500 ); }); } ( function () { interview( 1 ) .then( () => { return interview( 2 ); }) .then( () => { return interview( 3 ); }) .then( () => { console .log( " Every round of interview is successful! I smile happily" ); }) .catch( ( err ) => { console .log( ` Failed interview in round ${err.round} ` ); }); })(); Copy code

The .then.catch of Promise turns the callback hell into a piece of linear code!

Promise realization of multi-company interviews-parallel

//round function interview ( name ) { return new Promise ( function ( resolve, reject ) { setTimeout ( () => { if ( Math .random()> 0.4 ) { //resolve, reject can only be accepted A parameter resolve( "success" ); } else { const error = new Error ( "fail" ); reject({ name, error }); } }, 500 ); }); } ( function () { Promise .all([interview( "tenxun" ), interview( "ali" ), interview( "baidu" )]) .then( () => { console .log( "Every company has a successful interview" ); }) .catch ( ( ERR ) => { Console .log ( `interview $ {err.name} failed ' ); }); })(); Copy code

At last

The article is simple and crude, welcome to see your opinions left in the official comment area!

Students who feel rewarded are welcome to like and follow a wave!

Previous articles