13-async/await

113 阅读1分钟

async/await

是async/await: 是Promise + Generator的语法糖

  • async是对函数的修饰 -> async function xxx(){...}
    • 让函数的返回值自动变成promise实例
      • 如果不报错不返回值,默认返回 Promise{undefined}
      • 不报错返回值,Promise{[返回值]}
      • 报错:Reject,返回值是报错的原因
    • 可以在函数中使用await
      • await可以监听Promise的状态,从而决定做啥事
      • 必须出现在一个async修饰过的函数,否则报错
      • await 14 -> await Promise.resolve(14);
      • await 会等待状态成功时候,把await下面的代码执行
      • 如果await的状态是失败就,下面的不会执行了
// async/await: 是Promise + Generator的语法糖
const sleep = (interval = 1000) => {
  return new Promise(resolve => {
    resolve();
  })
}

sleep()
  .then(() => {
    console.log('one');
    sleep(100);
  })
  .then(() => {
    console.log("two");
    sleep(500);
  })
  • 用async/await重写一下上面的
(async function() {
  await sleep(100);

  await sleep(200);
  console.log(2)
  await sleep(100);
  console.log(3)
})();

image.png

例子

const fn = async () => {
  return 10;
}
const fn1 = async () => {}
const fn2 = async () => {
  throw new Error('123');
}

console.log(fn())
console.log(fn1())
console.log(fn2())

image.png

模拟调用接口

  • 一般用try/catch来捕获异常
const getData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if(Math.random() - 0.5 > 0) {
        resolve({
          code: 0,
          data: [1, 2, 3, 4]
        });
      } else {
        reject('请求失败');
      }
    }, 2000);
  })
}

(async function() {
  try {
    let num = await Promise.resolve(100);
    console.log(num);
    let data = await getData();
    console.log(data);
  }catch(err) {
    console.log(err);
  }
})();

image.png image.png

  • 例子2
const handler = async() => {
  await sleep(200);
  await sleep(500);
  await sleep(500);
  Math.random() - 0.5 > 0? "" : Promise.reject('error');
}
handler().then(() => {
  console.log("await都处理完了,状态都是fulfilied")
}).catch(() => {
  console.log("报错了嘻嘻")
})

image.png