Promise,async/await

ES6进阶

复习Promise

async function

面试官问asyc是干什么的?

  • 能和promise结合起来使用

  • 会让异步函数更像同步函数

例子

function fn() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let n = parseInt(Math.random() * 6 + 1, 10); //[1,7)
      resolve(n);
    }, 3000);
  });
}
fn().then(
  (x) => {
    console.log("successfull", x);
  },
  () => {
    "fail";
  }
);

codesanbox

async/await

await只能放在async函数里面,否则直接报错。

await后面接一个会return new Promise()的函数,并执行这个函数

另一个例子

面试题:为什么要用await?

为了更像是标准的同步函数(从上往下执行的)

The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

同步代码:synchronous code

promise的链式代码图示,会把你搞爆炸:

Screen Shot 2022-01-26 at 11.00.43 AM

await的局限性:只能接一个promise

如果需要多摇几个骰子的话,await就无法满足要求了。

因此需要用到promise.all

condition1和condition2同时成功才会触发success,其中任何一个失败都会触发fail

如何用await来实现接受多个promise呢?

promise.race只要有一个条件成功就会触发success

async和await都是promise的语法糖

最后更新于

这有帮助吗?