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 awaypromiseThe result at this timepromiseInpendingstatus
- You must wait for a period of time to get itpromiseThe result at this timepromiseInfulfilledstatus
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 awaypromiseThe result at this timepromiseInpendingstatus
- You must wait for a period of time to get itpromiseThe result at this timepromiseInrejectstatus
Note: if
pengdingState intorejectStatus, 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
- pendingCan only flow toresolveorreject;
- resolvewithrejectCan'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
- thenYespromiseThe state flow goes toresloveState 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
.then .catch summary
- resolvedThe state of the Promise will call back the first one afterwards.then
- rejectedThe state of the Promise will call back the first one afterwards.catch
- anyone rejectedThere is no behind the state cut.catchPromise 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,
- If the callback function ends up beingthrow, Then enter rejected
- If the callback function ends up beingreturn, 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
- If the callback function ends up beingthrow, Then enter rejected
- If the callback function ends up beingreturn, 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
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
- The most complete ECMAScript strategy
- What is the principle of QR code scan code login
- 15 front-end high-definition knowledge maps, strongly recommended to collect
- Centos/Docker/Nginx/Node/Jenkins operations that front-end developers should know ( long article)
- Let me tell you some powerful NPM packages