async/await的用法

220 阅读1分钟

为什么要用async?

promise().then(f1,f2).then(f3,f4)它不香吗?为什么还需要用awite呢?

简单来说,就是对同步的追求,虽然写起来麻烦,但是看起来更易懂。

async是可以和promise结合使用的函数,同时它可以将异步函数变得更像是标准的同步函数

普通的promise函数:

doSomething()
.then(result => doSomethingElse(value))
.then(newResult => doThirdThing(newResult))
.then(finalResult => console.log(`Got the final result: ${finalResult}`))
.catch(failureCallback);

利用async和await:

async function foo() {
  try {
    const result = await doSomething();
    const newResult = await doSomethingElse(result);
    const finalResult = await doThirdThing(newResult);
    console.log(`Got the final result: ${finalResult}`);
  } catch(error) {
    failureCallback(error);
  }
}
// 更像是同步函数

如果要使用await,那么必须用async函数把它包裹起来

await函数无法同时接受两个promise,即还需要promise.all或promise.race来实现,async/await更像是promise的语法糖,使基本的promise函数更加易懂。