据我所知,在ES7/ES2016中,将多个await代码放在代码中将类似于.then()使用promise 进行链接,这意味着它们将一个接一个地执行,而不是在并行执行.所以,例如,我们有这个代码:
await someCall();
await anotherCall();
Run Code Online (Sandbox Code Playgroud)
我是否理解正确,anotherCall()只有在someCall()完成后才会被调用?并行调用它们的最优雅方式是什么?
我想在Node中使用它,所以也许有一个async库的解决方案?
编辑:我对这个问题中提供的解决方案不满意:由于异步生成器中的非并行等待承诺而减速,因为它使用生成器而我正在询问更一般的用例.
之间有什么区别:
const [result1, result2] = await Promise.all([task1(), task2()]);
Run Code Online (Sandbox Code Playgroud)
和
const t1 = task1();
const t2 = task2();
const result1 = await t1;
const result2 = await t2;
Run Code Online (Sandbox Code Playgroud)
和
const [t1, t2] = [task1(), task2()];
const [result1, result2] = [await t1, await t2];
Run Code Online (Sandbox Code Playgroud) 以下代码片段给了我相同的结果。使用.then和async/await来获取数据有什么区别?
// Code 1
function fetchData() {
fetch(url)
.then(response => response.json())
.then(json => console.log(json))
}
// Code 2
async function fetchData() {
const response = await fetch(url);
const json = await response.json();
console.log(json);
}
Run Code Online (Sandbox Code Playgroud) javascript ×3
async-await ×2
asynchronous ×1
babeljs ×1
ecmascript-6 ×1
fetch ×1
node.js ×1
promise ×1