关于回调的终极解决方案

2019-03-18  本文已影响0人  雪映月圆

使用async和await把异步变成同步

    <script>
      function shaoshui() {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            if (Math.random() > 0.5) {
              console.log("烧水完成");
              resolve("开水");
            } else {
              console.log("停电了");
              reject("错误信息");
            }
          }, 1000);
        });
      }

      // 1. 在声明函数时,加上async关键字, 就可以在函数内部使用 await 关键字了
      // 2. await 后面必须跟 Promise 的实例化对象
      // 3. 在Promise中的两个信号弹中传递的参数,将会作为 await shaoshui()执行的结果返回
      async function doSomething() {
        try {
          const res = await shaoshui();
          console.log(res);
          console.log(1);
        } catch (error) {
          console.log(error);
        }
        const res2 = await shaoshui();
        const res3 = await shaoshui();
      }
      doSomething();
    </script>
上一篇 下一篇

猜你喜欢

热点阅读