Home>Article>Web Front-end> An in-depth analysis of Promise in Nodejs asynchronous programming

An in-depth analysis of Promise in Nodejs asynchronous programming

青灯夜游
青灯夜游 forward
2021-07-07 11:44:50 1619browse

This article will take you to understandNodejsPromise in asynchronous programming and introduce how Promise is better than callback.

An in-depth analysis of Promise in Nodejs asynchronous programming

[Recommended learning: "nodejs tutorial"]

What is Promise

Promise is an asynchronous Programming solutions!

  • The current event loop cannot get the result, but the future event loop will give you the result
  • It is a state machine
    • pengding
    • resolved
    • reejectd

Look at the status flow from the code

Pending to resolve flow test

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

Print out the following content

An in-depth analysis of Promise in Nodejs asynchronous programming

The result is in line with our expectations

  • We cannot get it immediatelypromiseresult, at this timepromiseis inpendingstate
  • You must wait for a period of time before you can get the result ofpromise, at this timepromiseIn thefulfilledstate

Pending to reject flow test

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

Print out the following content

An in-depth analysis of Promise in Nodejs asynchronous programming

The result is in line with our expectations

  • We cannot get the result ofpromiseimmediately, at this timepromiseInpendingstate
  • You must wait for a period of time before you can get the result ofpromise. At this time,promiseis inrejectStatus

Note: If the error is not captured correctly when thepengdingstate enters therejectstate, this error will be thrown To the global of JS

reslove status flow to reject status 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); })();

Print out the following content

An in-depth analysis of Promise in Nodejs asynchronous programming

It can be found!

At 300ms, the state ofpromisehas been switched toresolve. After switching, it will never reach therejectstate

  • pendingcan only be transferred toresolveorreject;
  • resolveandrejectCannot be transferred to each other;

Use then,catch to capture the result of 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); })();

Print the following content

An in-depth analysis of Promise in Nodejs asynchronous programming

It can be found that

  • thenis the result that can be obtained from the state ofpromiseto thereslovestate
(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); })();

Print out the following content

An in-depth analysis of Promise in Nodejs asynchronous programming

You can find that

catchispromiseThe state flows to therejectstate where the result can be obtained, and the previous global JS error can be captured bycatch

.then .catch summary

  • resolvedThe state's Promise will call back the first.then
  • rejectedThe Promise of the state will call back the first.catch
  • Anyrejectedstate will switch back A Promise without.catchwill cause a global error in the Js environment

The advantages of Promise compared to callback

Solving 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 只能接受一个参数 resolve("success"); } else { reject(new Error("fail")); } }, 1000); }); } (function () { const res = interview(); res .then((result) => { console.log("面试成功!我笑了"); }) .catch((error) => { console.log("面试失败!我哭了"); }); })();
## Test the situation where an error is thrown in

#.then
function interview() { return new Promise(function (resolve, reject) { setTimeout(() => { if (Math.random() > 0.4) { // resolve, reject 只能接受一个参数 resolve("success"); } else { reject(new Error("fail")); } }, 500); }); } (function () { const promsie1 = interview(); const promsie2 = promsie1.then((result) => { throw new Error("面试成功!我笑了,但是我拒绝了"); }); setTimeout(() => { console.log("promsie1", promsie1); console.log("promsie2", promsie2); }, 800); })();

An in-depth analysis of Promise in Nodejs asynchronous programming

As can be seen from the above code,

**.thenreturns a A brand new Promise, the result status of this Promise is determined by the result of the callback function of.then

  • If the callback function eventually isthrow, then enter rejected
  • If the callback function eventually isreturn, then enter resolved

.catch Test under normal conditions
function interview() { return new Promise(function (resolve, reject) { setTimeout(() => { if (Math.random() > 0) { // resolve, reject 只能接受一个参数 resolve("success"); } else { reject(new Error("fail")); } }, 500); }); } (function () { const promsie1 = interview(); const promsie2 = promsie1.catch((result) => { return "虽然面试失败,但我还是笑了"; }); setTimeout(() => { console.log("promsie1", promsie1); console.log("promsie2", promsie2); }, 800); })();

An in-depth analysis of Promise in Nodejs asynchronous programming

.catch返回一个全新的 Promise, 此 Promise 的结果状态是由.catch的回调函数的结果来决定的

  • 如果回调函数最终是throw, 则进入 rejected
  • 如果回调函数最终是return,则进入 resolved

.catch,.then 里面再返回 Promise

function interview() { return new Promise(function (resolve, reject) { setTimeout(() => { if (Math.random() > 0.4) { // resolve, reject 只能接受一个参数 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("面试成功!,给我400ms 总结一下"); }, 400); }); }) .catch((result) => { return new Promise(function (resolve, reject) { setTimeout(() => { resolve("面试失败,给我400ms 总结一下"); }, 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); })();

An in-depth analysis of Promise in Nodejs asynchronous programming

如果在.catch,.then中 返回 Promise, 则会等待此 Promise 的执行结果

如果回调函数最终 return 了 Promise,该 promise 和回调函数的 return 的 Promsie 状态保持一致, 这就表示了可以 在 Promise 的链式调用里面串行的执行多个异步任务!

Promise 实现多轮面试-串行

// round 面试第几轮 function interview(round) { return new Promise(function (resolve, reject) { setTimeout(() => { if (Math.random() > 0.4) { // resolve, reject 只能接受一个参数 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("每轮面试都成功!我开心的笑了"); }) .catch((err) => { console.log(`第${err.round}轮面试失败了`); }); })();

Promise 的 .then .catch 把回调地狱变成了一段线性的代码!

Promise 实现多加公司面试-并行

// round 面试第几轮 function interview(name) { return new Promise(function (resolve, reject) { setTimeout(() => { if (Math.random() > 0.4) { // resolve, reject 只能接受一个参数 resolve("success"); } else { const error = new Error("fail"); reject({ name, error }); } }, 500); }); } (function () { Promise.all([interview("tenxun"), interview("ali"), interview("baidu")]) .then(() => { console.log("每家公司都面试成功了"); }) .catch((err) => { console.log(`面试${err.name}失败了`); }); })();

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of An in-depth analysis of Promise in Nodejs asynchronous programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete