ES6 - async await

2022-03-31  本文已影响0人  恒星的背影

async 是什么

async 用于声明一个异步函数,这个函数 return 的内容如果是 promise,则返回值是这个promise,否则是 Promise.resolve(内容)

示例代码:

async function fn() {
  return 1
}

fn().then(v => {
  console.log(v)
})
.catch(error => {
  console.log(error)
})

async函数内部抛出错误,会导致返回的 Promise 对象变为reject状态。

await 是什么

await 只能存在于 async 函数中,否则报错。
async 函数可以不包含 await。

代码示例:

const fs = require('fs');

//简单封装  fs封装成一个promise
const readFile = function (fileName){
  return new Promise((resolve, reject) =>{
    fs.readFile(fileName, (err, data) =>{
      if(err) reject(err);
      resolve(data);
    });
  });
}

async function fn(){
  let f1 = await readFile('data/a.txt');
  console.log(f1.toString());
}
fn();

如果 await 右侧不是 promise,则会被转换成 resolved promise。
await 左侧变量得到 promise resolve 的内容。

await 可以暂停 async 函数的执行,等待其右侧 promise 的处理,然后恢复 async 函数的执行并返回 resolve 的值。

两个例子

var sequentialStart = async function() {
  const slow = await resolveAfter2Seconds();
  const fast = await resolveAfter1Second();

  console.log(slow);
  console.log(fast);
}

var concurrentStart = async function() {
  const slow = resolveAfter2Seconds();
  const fast = resolveAfter1Second();

  console.log(await slow);
  console.log(await fast); 
}

前者是第一个异步操作完成后,第二个异步操作才开始执行。
后者是两个异步操作同时开始,但处理数据是按固定顺序的。

async 的错误处理

为了出错后可以继续执行,可以在易出错的地方添加 try catch 处理:

async function getProcessedData(url) {
  let v;
  try {
    v = await downloadData(url); 
  } catch(e) {
  
  }
  return processDataInWorker(v);
}

也可以在await右侧的 promise 后面用 catch 处理:

async function fn(){
  await Promise.reject('出现问题了').catch(err=>{
    console.log(err);
  });
}

多个异步操作的时候,可以统一处理:

try{
  let f1 = await readFile('data/a.txt');
  let f3 = await readFile('data/c.txt');
  let f2 = await readFile('data/b.txt');
}catch(e){}

其它

promise.then() 中 return 的内容如果是 promise,则返回值是这个 promise,否则是 Promise.resolve(内容) 。
Promise.reject() 相当于抛出错误,后续的代码不会继续执行。

疑问

event loop
new promise 传入的函数会立即同步执行,直接 resolve 也会立即改变 promise 的状态,但是 .then() 传入的函数不会立即同步执行。
try 的语句块中有的错误会 throw,有的不 throw,所以 catch 只能捕获某些错误。

参考资料

async function | MDN
async 函数 - ECMAScript 6入门

上一篇 下一篇

猜你喜欢

热点阅读