等待承诺链有什么问题? [英] What's wrong with awaiting a promise chain?

查看:81
本文介绍了等待承诺链有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Angular 6应用程序,并被告知以下内容是反模式:

I’m working on an Angular 6 application and I’ve been told the following is an anti-pattern:

await someFunction().then(result => {
    console.log(result);
});

我意识到,等待承诺链毫无意义.如果someFunction()返回一个Promise,则在等待时不需要Promise链.您可以这样做:

I realize that it is pointless to await a promise chain. If someFunction() returns a promise, you don’t need a promise chain if you’re awaiting it. You can do this:

const result = await someFunction();
console.log(result);

但是有人告诉我,等待诺言链可能会导致错误,或者会破坏代码中的内容.如果上面的第一个代码段与第二个代码段执行相同的操作,那么使用哪个代码段有什么关系呢.第一个摘要介绍第二个摘要没有带来什么危险?

But I’m being told awaiting a promise chain can cause bugs, or that it will break things in my code. If the first code snippet above does the same thing as the second snippet, what does it matter which one is used. What dangers does the first snippet introduce that the second one doesn’t?

推荐答案

在幕后,异步/等待只是承诺.

Under the hood, async/await is just promises.

也就是说,当您有一些类似于以下代码的代码:

That is, when you have some code that looks like:

const result = await myAsyncFunction();   
console.log(result): 

与写作完全相同:

myAsyncFunction().then(data => {
   const result = data; 
   console.log(result); 
}); 

当时的原因-您不应该混合使用async/await和.then链-是因为它令人困惑.

The reason then - that you shouldn't mix async/await and .then chains - is because it's confusing.

最好只选择一种样式并坚持下去.

It's better to just pick one style, and stick to it.

在选择一个时-您最好也选择async/await-这更容易理解.

And while you're picking one - you might as well pick async/await - it's more understandable.

这篇关于等待承诺链有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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