Mev*_*via 3 javascript async-await
根据这篇文章:https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8
似乎可以使用以下语法:
let [foo, bar] = await Promise.all([getFoo(), getBar()]);
Run Code Online (Sandbox Code Playgroud)
用于多个承诺执行.但是在使用它的时候我得到了Uncaught SyntaxError: Unexpected identifier.
我如何使用async/await和promise.all实现多个同时执行的操作,并通过响应解决.
----- EDITED
我在里面使用的功能promise.all就是这个:
async function getJson(callback) {
try {
let response = await fetch('URL_LINK_HERE');
let json = await response.json();
return json;
} catch(e) {
console.log('Error!', e);
}
}
Run Code Online (Sandbox Code Playgroud)
作为测试领域,我正在使用谷歌浏览器版本 60.0.3112.113
您的代码很可能看起来像这样:
var thingsDone = await Promise.all([
Promise.resolve("eat"),
Promise.resolve("sleep")
]);
console.log(thingsDone);Run Code Online (Sandbox Code Playgroud)
这不起作用,因为await关键字仅在async函数内有效(全局上下文不是).它只会导致语法错误.
处理此问题的一种方法是将其用作常规旧承诺而不使用await关键字:
Promise.all([
Promise.resolve("eat"),
Promise.resolve("sleep")
]).then((thingsDone) => console.log(thingsDone));Run Code Online (Sandbox Code Playgroud)
或者如果你想获得想象力(或者需要更多空间来编写表达式函数),请将逻辑包装在async函数中,然后像承诺一样处理它:
async function doThings() {
var eat = await Promise.resolve("eat");
var sleep = await Promise.resolve("sleep");
return Promise.all([Promise.resolve(eat), Promise.resolve(sleep)]);
}
doThings().then((thingsDone) => console.log(thingsDone));Run Code Online (Sandbox Code Playgroud)
这将允许您await根据需要使用,并且在更复杂的功能中更有用.
或者甚至更简洁地使用立即执行的async函数:
(async() => {
var eat = await Promise.resolve("eat");
var sleep = await Promise.resolve("sleep");
return Promise.all([Promise.resolve(eat), Promise.resolve(sleep)]);
})().then((thingsDone) => console.log(thingsDone));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2611 次 |
| 最近记录: |