Skip to main content

Command Palette

Search for a command to run...

Promise 异步编程

Published
2 min read
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
  // 打印顺序
  // Promise Hi Resolved.
  let promise = new Promise(function (resolve, reject) {
      console.log("Promise");
      // 这句话会调用,进入 fulfilled 状态
      resolve();
    });
    promise.then(function () {
      console.log("Resolved.");
    });
    console.log("Hi!");
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
console.log('hi');
let promise = new Promise(function (resolve, reject) {
  throw new Error("Explosion!");
});
// 打印顺序
// hi world Explosion!
// rejection 会执行
// Promise内部有个 try catch,reject(error)
promise.catch(function (error) {
  console.log(error.message);     // "Explosion!"
});
console.log('world');
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
  let rejected;
  window.onunhandledrejection = function (event) {
    console.log(event.type);
    console.log(event.reason.message);
    console.log(rejected === event.promise);
    // 这里会打印
    // "unhandledrejection"
    // "Explosion!"
    // true
  };
  window.onrejectionhandled = function (event) {
    console.log(event.type);
    console.log(event.reason.message);
    console.log(rejected === event.promise);
  };
  // 控制台会报错
  rejected = Promise.reject(new Error("Explosion!"));
  // rejected.catch(err => {
  //   console.log(err.message);
  // })
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
  let p1 = new Promise(function (resolve, reject) {
      resolve(42);
    });
    // 链式执行
    // then catch 执行后都会返回 pormise
    // 原理:执行后返回新的Promise.resolve(value)
    p1.then(function (value) {
      console.log(value);
    }).then(function () {
      console.log("Finished");
    });
</script>
</body>
</html>

原理

js引擎将promise添加到任务队列,并通过任务调度来延期执行她们。并创建另一个任务队列来跟踪promise的fulfillment 和 rejection 以确保这些处理执行无误。

promise有三种状态, pending、fulfilled、rejected。后两种情况,处理函数会被执行。then()方法允许添加 fulfillment 和 rejection。catch()方法允许添加 rejection 处理函数 。

每次处理then()方法,执行完毕后,会返回一个状态为 fulfilled 的 Promise。这样就可以链式调用了。

More from this blog

EddieQiao's blog

84 posts

coder, work in suzhou