美文网首页
ES7 async/await 踩坑记

ES7 async/await 踩坑记

作者: Jover | 来源:发表于2018-03-16 14:17 被阅读124次

ES7 async/await 的实现给我们带来了极大的方便,避免了回调地狱。
然后我要分享的是,我在使用async/await中遇到的坑。

坑之一

在KOA2中这样写代码

async hello() {
    return 'hello world!'
}

app.use(async ctx => {
  ctx.body = {
     data: await hello(); // => 返回 "hello world!"
  };
  console.log(ctx.body); // => 正常输出 { data: "hello world!" }
  ctx.status = 200;
});

然而: 404! what???!!! 什么鬼?!!!

经研究发现,把上面代码改为:

async hello() {
    return 'hello world!'
}

app.use(async ctx => {
  const data = await hello();
  ctx.body = {
     data
  };
  console.log(ctx.body); // => 正常输出 { data: "hello world!" }
  ctx.status = 200;
});

即恢复正常。

坑之二

当我这样写的时候

const text = await getData().text; // 报错!因为await的优先级要小于 . 运算符

改为以下即可正常:

const text = (await getData()).text;

当然,严格来说,这不是坑,仅仅为需要注意的地方,我将其例入其中。

等待后续加入.....

避坑指南

以,是async的实现方式特性造成的(根据await对代码进行切片),暂时没有时间去细究其中原理。
在这里也特别说明一下为了避免以上情况出现,我们在使用 async/await的时候记录养成以下习惯,避免踩坑。

  • await调用代码尽量单独一行,例如
// 推荐写法
await getData();
  • 避免直接将值await调用当作函数实参传递,例如:
// 错误写法
save(await getData());
// 正确写法
const data = await getData();
save(data);

避免将await调用赋给object对象属性,例如:

// 错误写法
const obj = {
  data: await getData()
}
// 正确写法
const data = await getData();
const obj = {
  data
}

相关文章

网友评论

      本文标题:ES7 async/await 踩坑记

      本文链接:https://www.haomeiwen.com/subject/frnlqftx.html