Home>Article>Web Front-end> An in-depth analysis of Promise in Nodejs asynchronous programming
This article will take you to understandNodejsPromise in asynchronous programming and introduce how Promise is better than callback.
[Recommended learning: "nodejs tutorial"]
Promise is an asynchronous Programming solutions!
(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
The result is in line with our expectations
promise
result, at this timepromise
is inpending
statepromise
, at this timepromise
In thefulfilled
state(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
The result is in line with our expectations
promise
immediately, at this timepromise
Inpending
statepromise
. At this time,promise
is inreject
StatusNote: If the error is not captured correctly when the
pengding
state enters thereject
state, this error will be thrown To the global of JS
(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
It can be found!
At 300ms, the state ofpromise
has been switched toresolve
. After switching, it will never reach thereject
state
pending
can only be transferred toresolve
orreject
;resolve
andreject
Cannot be transferred to each other;(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
It can be found that
then
is the result that can be obtained from the state ofpromise
to thereslove
state(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
You can find that
catch
ispromise
The state flows to thereject
state where the result can be obtained, and the previous global JS error can be captured bycatch
.then .catch summary
resolved
The state's Promise will call back the first.then
rejected
The Promise of the state will call back the first.catch
rejected
state will switch back A Promise without.catch
will cause a global error in the Js environmentLet’s continue the previous interview example
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
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); })();
**.thenreturns a A brand new Promise, the result status of this Promise is determined by the result of the callback function of
.then
, then enter rejected
, then enter resolved
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); })();
.catch
返回一个全新的 Promise, 此 Promise 的结果状态是由.catch
的回调函数的结果来决定的
throw
, 则进入 rejectedreturn
,则进入 resolvedfunction 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); })();
如果在.catch
,.then
中 返回 Promise, 则会等待此 Promise 的执行结果
如果回调函数最终 return 了 Promise,该 promise 和回调函数的 return 的 Promsie 状态保持一致, 这就表示了可以 在 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 把回调地狱变成了一段线性的代码!
// 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!