使用异步/等待与使用Promises有何不同? [英] How does using async/await differ from using Promises?

查看:38
本文介绍了使用异步/等待与使用Promises有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我开始使用(Async& Await).在此之前,我使用Promise使我的过程成为异步的.喜欢:

Recently I started using (Async & Await). Before this, I used Promise to make my process Asynchronous. Like:

example.firstAsyncRequest()
.then(firstResponse => {
    return example.secondAsyncRequest(firstResponse)
})
.then(secondResponse => {
    return example.thirdAsyncRequest(secondResponse)
})
.then(result => {
    console.log(result)
})
.catch(err => {
    console.log(err)
})

现在,我正在实现以下目标:

Now I am achieving this like:

  try {
    const firstResponse = await example.firstAsyncRequest();
    const secondResponse = await example.secondAsyncRequest(firstResponse);
    const thirdAsyncRequest = await example.thirdAsyncRequest(secondResponse);
    console.log(thirdAsyncRequest)
  }
  catch (error) {
    // Handle error
  }

在这两种方法中,代码块方法都一个接一个地执行,最后抛出错误(如果有)并被 catch 块捕获.我的问题是,这仅是语法上的区别吗?请解释或建议我任何链接以更好地理解这一点.

In both, the code-block method executes one after another and finally throws an error if any and gets caught by catch block. My question is, is this only a difference of syntax? Please explain or suggest me any link to understand this better.

谢谢

推荐答案

语法上只有区别吗?

Is there only difference of syntax?

是的.您的示例在功能上等同于 ,只是缺少第二个示例

Yes. Your examples are functionally equivalent except that your second example is missing

console.log(thirdAsyncRequest);

...在第三个 await 之后.(该变量实际上应该是 result 以匹配第一个代码块,或者是 thirdResponse 以匹配其他两个响应变量).

...after the third await. (That variable really should be result to match the first code block, or thirdResponse to match the other two response variables).

async / await 是围绕诺言创建和使用的语法糖.它真的很有用糖,但是仅此而已. async 函数返回承诺, await 表达式等效于 then 回调,以及 try / catch 周围的 await 表达式等效于 catch 回调.

async/await is syntactic sugar around promise creation and consumption. It's really helpful sugar, but that's all it is. async functions return promises, await expressions are the equivalent of then callbacks, and try/catch around await expressions is the equivalent of a catch callback.

这篇关于使用异步/等待与使用Promises有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆