【发布时间】:2021-03-08 04:56:01
【问题描述】:
我找到了这个示例 sn-ps in this article :
<script>
async function get_data() { // async function
await $.get('https://url.com/one')
await $.get('https://url.com/two')
let res = await $.get('https://url.com/three')
console.log(res)
}
</script>
承诺的版本是:
<script>
function get_data() {
$.get('https://url.com/one', () => {
$.get('https://url.com/two', () => {
$.get('https://url.com/three', (res) => {
console.log(res)
})
})
})
}
</script>
我的问题是,在承诺的版本中,我们可以将
await $.get('https://url.com/one') 变成<strike>await</strike> $.get('https://url.com/one'),因为它是第一个承诺吗?如果是,为什么两者中的任何一个都被视为最佳实践?
先感谢您
【问题讨论】:
-
不,你不能删除等待,如果你删除等待,那么函数将返回一个未解决的承诺
-
await让承诺等到它解决。没有它,它将启动请求并继续下一行而无需等待
标签: javascript node.js async-await ecmascript-2017