async/await提供了一种使用同步样式代码异步访问资源的选项,而不会阻塞主线程。然而,使用它有点棘手。在本文中,我们将从不同的角度探讨async / await,并将展示如何正确有效地使用它们。

async / await的好处

async/await给我们带来的最重要的好处是同步编程风格。我们来看一个例子吧。

// async / await
async getBooksByAuthorWithAwait(authorId){
const books = await bookModel.fetchAll();
return books.filter(b => b.authorId === authorId);
}
// promise
getBooksByAuthorWithPromise(authorId){
return bookModel.fetchAll()。then(
books => books.filter(b => b.authorId === authorId));
}

很明显,async/await版本比承诺版本更容易理解。

另一个不太明显的好处是async关键字。它声明getBooksByAuthorWithAwait()函数返回值保证是一个promise,以便调用者可以调用getBooksByAuthorWithAwait().then(...)await getBooksByAuthorWithAwait()安全。想想这个例子(不好的做法!):

getBooksByAuthorWithPromise(authorId){
if(!authorId){
return null;
}
return bookModel.fetchAll()。then(
books => books.filter(b => b.authorId === authorId));
}

在上面的代码中,getBooksByAuthorWithPromise可以返回一个promise(正常情况)或一个null值(例外情况),在这种情况下,调用者不能.then()安全地调用  。而通过async声明,就可以安全的用.then()调用了。

Async/await可能会产生误导

有些文章将async / await与Promise进行比较,并声称它是JavaScript异步编程演变的下一代,我不同意。Async / await是一种改进,但它只不过是一种语法糖,它不会完全改变我们的编程风格。

从本质上讲,异步函数仍然是承诺。在正确使用异步函数之前,您必须了解promises,更糟糕的是,大多数情况下您需要使用promises和异步函数。

考虑上面示例中的getBooksByAuthorWithAwait()getBooksByAuthorWithPromises()函数。请注意,它们不仅在功能上相同,而且具有完全相同的界面!

getBooksByAuthorWithAwait()如果直接调用,这意味着将返回一个承诺。

嗯,这不一定是坏事。只有这个名字await让人感觉“哦,这可以将异步函数转换为同步函数”,这实际上是错误的。

Async/await陷阱

那么使用async/await时会出现什么错误?这是一些常见的。

太顺序了

虽然await可以使您的代码看起来像同步,但请记住它们仍然是异步的,必须注意避免过于顺序。

async getBooksAndAuthor(authorId){
const books = await bookModel.fetchAll();
const author = await authorModel.fetch(authorId);
return {
author,
books:books.filter(book => book.authorId === authorId),
};
}

此代码看起来逻辑正确。但这是错误的。

  1. await bookModel.fetchAll()将等到fetchAll()返回。
  2. 然后await authorModel.fetch(authorId)将被执行。

请注意,authorModel.fetch(authorId)它不依赖于bookModel.fetchAll()的结果,实际上它们可以并行调用!但是,在这里使用了await,这两个调用变为顺序,并且总执行时间将比并行版本长得多。

这是正确的方法:

async getBooksAndAuthor(authorId){
const bookPromise = bookModel.fetchAll();
const authorPromise = authorModel.fetch(authorId);
const book = await bookPromise;
const author = await authorPromise;
return {
author,
books:books.filter(book => book.authorId === authorId),
};
}

或者更糟糕的是,如果你想逐个获取一个项目列表,你必须依赖Promise:

async getAuthors(authorIds){
// 错误,这将导致顺序调用
// const authors = _.map(
// authorIds,
// id => await authorModel.fetch(id));
// 正确
const promises = _.map(authorIds,id => authorModel.fetch(id));
const authors = await Promise.all(promises);
}

简而言之,您仍然需要异步考虑工作流,然后尝试await同步编写代码。在复杂的工作流程中,直接使用promises可能更容易。

【译】JavaScript async / await:好的部分,陷阱和如何使用的更多相关文章

  1. JavaScript async/await:优点、陷阱及如何使用

    翻译练习 原博客地址:JavaScript async/await: The Good Part, Pitfalls and How to Use ES7中引进的async/await是对JavaSc ...

  2. JavaScript async/await 基础知识

    async 作用: async函数返回一个 Promise对象,无论内部有没有await关键字. await 作用: await等待的是一个表达式,这个表达式的计算结果是 Promise 对象 或者是 ...

  3. 【译】Async/Await(一)——多任务

    原文标题:Async/Await 原文链接:https://os.phil-opp.com/async-await/#multitasking 公众号: Rust 碎碎念 翻译 by: Praying ...

  4. 【译】Async/Await(二)——Futures

    原文标题:Async/Await 原文链接:https://os.phil-opp.com/async-await/#multitasking 公众号: Rust 碎碎念 翻译 by: Praying ...

  5. 【译】Async/Await(三)——Aysnc/Await模式

    原文标题:Async/Await 原文链接:https://os.phil-opp.com/async-await/#multitasking 公众号: Rust 碎碎念 翻译 by: Praying ...

  6. 【译】Async/Await(四)—— Pinning

    原文标题:Async/Await 原文链接:https://os.phil-opp.com/async-await/#multitasking 公众号: Rust 碎碎念 翻译 by: Praying ...

  7. 【译】Async/Await(五)—— Executors and Wakers

    原文标题:Async/Await 原文链接:https://os.phil-opp.com/async-await/#multitasking 公众号: Rust 碎碎念 翻译 by: Praying ...

  8. JavaScript - async/await 基础示例

    一个函数如果被 async 修饰,无论内部是否有 await的异步操作,都会返回一个 Promise 对象 demo 1 async function basicAsync() { let resul ...

  9. 七 vue学习 async/await

    1:  javaScript async/await: 调用async函数的时候,是异步的,函数后面的代码继续执行.! async / await是ES7的重要特性之一,也是目前社区里公认的优秀异步解 ...

随机推荐

  1. ARTS第十周

     之前忘了发布 1.Algorithm:每周至少做一个 leetcode 的算法题2.Review:阅读并点评至少一篇英文技术文章3.Tip:学习至少一个技术技巧4.Share:分享一篇有观点和思考的 ...

  2. Ubuntu中Docker的安装与使用

    Ubuntu中安装Docker 更新ubuntu的apt源索引 sudo apt-get update 2.安装包允许apt通过HTTPS使用仓库 sudo apt-get install \ apt ...

  3. python使用笔记19--网络操作

    1.get请求 1 import requests 2 import datetime 3 #get请求 4 url = 'http://api.nnzhp.cn/api/user/stu_info' ...

  4. C语言:float表示范围

    #include <stdio.h> #include <limits.h> //整数限制 #include <float.h> //浮点数限制 void main ...

  5. c语言字符串存储方式

    #include <stdio.h> // C 语言中,任何数据类型都不可以直接存储一个字符串.那么字符串如何存储? //在 C 语言中,字符串有两种存储方式,一种是通过字符数组存储,另一 ...

  6. Java基础00-基础知识练习12

    1. 减肥计划 1.1 if语句实现 import java.util.Scanner; public class Demo01 { public static void main(String[] ...

  7. 基于SSM酒店管理系统mysql版本(前后台)

    介绍:spring,springmvc,mybatis,mysql,eclipse 截图: 数据库表:CREATE TABLE `account` ( `id` int(11) NOT NULL AU ...

  8. pytorch中网络特征图(feture map)、卷积核权重、卷积核最匹配样本、类别激活图(Class Activation Map/CAM)、网络结构的可视化方法

    目录 0,可视化的重要性: 1,特征图(feture map) 2,卷积核权重 3,卷积核最匹配样本 4,类别激活图(Class Activation Map/CAM) 5,网络结构的可视化 0,可视 ...

  9. POJ1723,1050,HDU4864题解(贪心)

    POJ1723 Soldiers 思维题. 考虑y坐标,简单的货舱选址问题,选择中位数即可. 再考虑x坐标,由于直接研究布置方法非常困难,可以倒着想:不管如何移动,最后的坐标总是相邻的,且根据贪心的思 ...

  10. ubuntu16登录后黑屏无法进入系统问题汇总

    今晚在使用虚拟机的过程中发现有些卡顿,顿时想给虚拟机增加内核数,然后,然后,,,我就再也没有看到过图形化界面,在某搜索引擎查找了半天,把我的问题汇总了一下发出来,希望对遇到同样问题的有所帮助. 出现黑 ...