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

An in-depth analysis of Promise in Nodejs asynchronous programming

青灯夜游
Release: 2021-07-09 10:09:19
forward
1725 people have browsed it

This article will take you to understand Nodejs Promise 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);
})();
Copy after login

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 immediatelypromise result, at this time promise is in pending state
  • You must wait for a period of time before you can get the result of promise, at this timepromiseIn the fulfilled state

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);
})();
Copy after login

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 of promise immediately, at this timepromiseIn pending state
  • You must wait for a period of time before you can get the result of promise. At this time, promise is in reject Status

Note: If the error is not captured correctly when the pengding state enters the reject state, 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);
})();
Copy after login

Print out the following content

An in-depth analysis of Promise in Nodejs asynchronous programming

It can be found!

At 300ms, the state of promise has been switched to resolve. After switching, it will never reach the reject state

  • pending can only be transferred to resolve or reject;
  • resolve and reject Cannot 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);
})();
Copy after login

Print the following content

An in-depth analysis of Promise in Nodejs asynchronous programming

It can be found that

  • then is the result that can be obtained from the state of promise to the reslove 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);
})();
Copy after login

Print out the following content

An in-depth analysis of Promise in Nodejs asynchronous programming

You can find that

catch is promise The state flows to the reject state where the result can be obtained, and the previous global JS error can be captured by catch

.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
  • Any rejected state will switch back A Promise without .catch will 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("面试失败!我哭了");
    });
})();
Copy after login
## 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);
})();
Copy after login

An in-depth analysis of Promise in Nodejs asynchronous programming

As can be seen from the above code,

**.then returns 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 is return, 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);
})();
Copy after login

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);
})();
Copy after login

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}轮面试失败了`);
    });
})();
Copy after login

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}失败了`);
    });
})();
Copy after login

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

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!

source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template