JavaScript 承诺和异步等待之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34401389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:17:22  来源:igfitidea点击:

What is the difference between JavaScript promises and async await?

javascriptasynchronousreactjsasync-awaitpromise

提问by bozzmob

I have been using ECMAScript 6and ECMAScript 7 features already (thanks to Babel) in my applications - both mobile and web.

我已经在我的应用程序中使用了ECMAScript 6和 ECMAScript 7 特性(感谢 Babel)——移动和网络。

The first step obviously was to ECMAScript 6 levels. I learnt many async patterns, the promises (which are really promising), generators (not sure why the * symbol), etc. Out of these, promises suited my purpose pretty well. And I have been using them in my applications quite a lot.

第一步显然是达到 ECMAScript 6 级别。我学习了许多异步模式、promise(确实很有前途)、生成器(不确定为什么是 * 符号)等。其中,promise 非常适合我的目的。我一直在我的应用程序中使用它们很多。

Here is an example/pseudocode of how I have implemented a basic promise-

这是我如何实现基本承诺的示例/伪代码-

var myPromise = new Promise(
    function (resolve,reject) {
      var x = MyDataStore(myObj);
      resolve(x);
    });

myPromise.then(
  function (x) {
    init(x);
});

As time passed, I came across ECMAScript 7 features, and one of them being ASYNCand AWAITkeywords/functions. These in conjunction do great wonders. I have started to replace some of my promises with async & await. They seem to add great value to programming style.

随着时间的流逝,我碰到的ECMAScript来到7层的功能,并把它们作为一个ASYNCAWAIT关键字/功能。这些结合起来创造了巨大的奇迹。我已经开始用async & await. 它们似乎为编程风格增添了巨大的价值。

Again, here is a pseudocode of how my async, await function looks like-

同样,这里是我的 async, await 函数的伪代码 -

async function myAsyncFunction (myObj) {
    var x = new MyDataStore(myObj);
    return await x.init();
}
var returnVal = await myAsyncFunction(obj);

Keeping the syntax errors (if any) aside, both of them do the exact same thing is what I feel. I have almost been able to replace most of my promises with async,awaits.

把语法错误(如果有的话)放在一边,我觉得它们都做同样的事情。我几乎可以用 async,await 代替我的大部分承诺。

Why is async,await needed when promises do a similar job?

当 Promise 做类似的工作时,为什么需要 async,await ?

Does async,await solve a bigger problem? Or was it just a different solution to callback hell?

async,await 是否解决了更大的问题?或者它只是回调地狱的不同解决方案?

As I said earlier, I am able to use promises and async,await to solve the same problem. Is there anything specific that async await solved?

正如我之前所说,我可以使用 promises 和 async,await 来解决同样的问题。async await 有什么具体解决的吗?

Additional notes:

补充说明:

I have been using async,awaits and promises in my React projects and Node.js modules extensively. React especially have been an early bird and adopted a lot of ECMAScript 6 and ECMAScript 7 features.

我一直在我的 React 项目和 Node.js 模块中广泛使用 async、await 和 promises。React 尤其是一个早期的鸟,并采用了许多 ECMAScript 6 和 ECMAScript 7 特性。

采纳答案by Josh Beam

Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem?

当 Promises 做类似的工作时,为什么需要 async,await ?async,await 是否解决了更大的问题?

async/awaitsimply gives you a synchronous feel to asynchronous code. It's a very elegant form of syntactical sugar.

async/await只是让您对异步代码有一种同步的感觉。这是一种非常优雅的语法糖形式。

For simple queries and data manipulation, Promises can be simple, but if you run into scenarios where there's complex data manipulation and whatnot involved, it's easier to understand what's going on if the code simply looksas though it's synchronous (to put it another way, syntax in and of itself is a form of "incidental complexity" that async/awaitcan get around).

对于简单的查询和数据操作,Promises 可以很简单,但是如果您遇到复杂的数据操作和不涉及的场景,如果代码看起来好像是同步的(换句话说,语法本身就是一种async/await可以绕过的“偶然复杂性”形式)。

If you're interested to know, you can use a library like co(alongside generators) to give the same sort of feel. Things like this have been developed to solve the problem that async/awaitultimately solves (natively).

如果您有兴趣知道,您可以使用像co(与生成器一起)之类的库来提供相同的感觉。已经开发了这样的东西来解决async/await最终解决的问题(本机)。

回答by Stephen Cleary

Async/Await provide a much nicer syntax in more complex scenarios. In particular, anything dealing with loops or certain other constructs like try/catch.

Async/Await 在更复杂的场景中提供了更好的语法。特别是处理循环或某些其他结构(如try/ )的任何内容catch

For example:

例如:

while (!value) {
  const intermediate = await operation1();
  value = await operation2(intermediate);
}

This example would be considerably more convoluted just using Promises.

仅使用 Promises,这个例子会更加复杂。

回答by Willem van der Veen

Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem? or was it just a different solution to callback hell? As I said earlier, I am able to use Promises and Async,Await to solve the same problem. Is there anything specific that Async Await solved?

当 Promises 做类似的工作时,为什么需要 async,await ?async,await 是否解决了更大的问题?或者它只是回调地狱的不同解决方案?正如我之前所说,我可以使用 Promises 和 Async,Await 来解决同样的问题。Async Await 解决了什么具体问题吗?

The first things you have to understand that async/awaitsyntax is just syntactic sugar which is meant to augment promises. In fact the return value of an asyncfunction is a promise. async/awaitsyntax gives us the possibility of writing asynchronous in a synchronous manner. Here is an example:

您首先必须了解async/await语法只是用于增强承诺的语法糖。事实上,async函数的返回值是一个promise。async/await语法为我们提供了以同步方式编写异步的可能性。下面是一个例子:

Promise chaining:

承诺链:

function logFetch(url) {
  return fetch(url)
    .then(response => response.text())
    .then(text => {
      console.log(text);
    }).catch(err => {
      console.error('fetch failed', err);
    });
}

Asyncfunction:

Async功能:

async function logFetch(url) {
  try {
    const response = await fetch(url);
    console.log(await response.text());
  }
  catch (err) {
    console.log('fetch failed', err);
  }
}

In the above example the awaitwaits for the promise (fetch(url)) to be either resolved or rejected. If the promise is resolved the value is stored in the responsevariable, and if the promise is rejected it would throw an error and thus enter the catchblock.

在上面的例子中,await等待承诺(fetch(url))被解决或拒绝。如果 promise 被解析,则值存储在response变量中,如果 promise 被拒绝,它将抛出错误并因此进入catch块。

We can already see that using async/awaitmight be more readable than promise chaining. This is especially true when the amount of promises which we are using increases. Both Promise chaining and async/awaitsolve the problem of callback hell and which method you choose is matter of personal preference.

我们已经可以看到,使用async/await可能比 promise 链接更具可读性。当我们使用的 Promise 数量增加时尤其如此。Promise 链和async/await解决回调地狱的问题以及您选择哪种方法取决于个人喜好。

回答by Bozhinovski

Full comparison with pros and cons.

利弊的全面比较。

Plain JavaScript

纯 JavaScript

  • Pros
  • 优点
  • Does not require any additional libraries or technology
  • O?ers the best performance
  • Provides the best level of compatibility with third-party libraries
  • Allows the creation of ad hoc and more advanced algorithms
  • 不需要任何额外的库或技术
  • 提供最佳性能
  • 提供与第三方库的最佳兼容性
  • 允许创建临时和更高级的算法
  • Cons
  • 缺点
  • Might require extra code and relatively complex algorithms
  • 可能需要额外的代码和相对复杂的算法

Async (library)

异步(库)

  • Pros
  • 优点
  • Simpli?es the most common control ?ow patterns
  • Is still a callback-based solution
  • Good performance
  • 简化最常见的控制流模式
  • 仍然是基于回调的解决方案
  • 很棒的表演
  • Cons
  • 缺点
  • Introduces an external dependency
  • Might still not be enough for advanced ?ows
  • 引入外部依赖
  • 对于高级流可能仍然不够

Promises

承诺

  • Pros
  • 优点
  • Greatly simpli?es the most common control ?ow patterns
  • Robust error handling
  • Part of the ES2015 speci?cation
  • Guarantees deferred invocation of onFulfilled and onRejected
  • 大大简化了最常见的控制流模式
  • 强大的错误处理
  • ES2015 规范的一部分
  • 保证延迟调用 onFulfilled 和 onRejected
  • Cons
  • 缺点
  • Requires promisify callback-based APIs
  • Introduces a small performance hit
  • 需要 promisify 基于回调的 API
  • 引入了一个小的性能影响

Generators

发电机

  • Pros
  • 优点
  • Makes non-blocking API look like a blocking one
  • Simpli?es error handling
  • Part of ES2015 speci?cation
  • 使非阻塞 API 看起来像阻塞 API
  • 简化错误处理
  • ES2015 规范的一部分
  • Cons
  • 缺点
  • Requires a complementary control ?ow library
  • Still requires callbacks or promises to implement non-sequential ?ows
  • Requires thunkify or promisify nongenerator-based APIs
  • 需要补充控制流库
  • 仍然需要回调或承诺来实现非顺序流
  • 需要 thunkify 或 promisify 非基于生成器的 API

Async await

异步等待

  • Pros
  • 优点
  • Makes non-blocking API look like blocking
  • Clean and intuitive syntax
  • 使非阻塞 API 看起来像阻塞
  • 简洁直观的语法
  • Cons
  • 缺点
  • Requires Babel or other transpilers and some con?guration to be used today
  • 需要 Babel 或其他转译器和一些今天使用的配置

回答by gafi

Async/await can help make your code cleaner and more readable in cases where you need complicated control flow. It also produces more debug-friendly code. And makes it possible to handle both synchronous and asynchronous errors with just try/catch.

在需要复杂控制流的情况下,Async/await 可以帮助使您的代码更清晰、更具可读性。它还生成更易于调试的代码。并且可以仅使用try/catch.

I recently wrote this post showing the advantages of async/await over promises in some common use cases with code examples: 6 Reasons Why JavaScript Async/Await Blows Promises Away (Tutorial)

我最近写了这篇文章,展示了在一些常见用例中 async/await 优于 promises 的代码示例:JavaScript Async/Await Blows Promises Away 的 6 个原因(教程)