我正在尝试使用 Promise.all() 函数对所有请求进行等待,而不是像这样手动执行所有获取:var data = await Promise.all([ fetch('https://jsonplaceholder.typicode.com/posts').then((response) => response.json()), fetch('https://jsonplaceholder.typicode.com/albums').then((response) => response.json()), fetch('https://jsonplaceholder.typicode.com/users').then((response) => response.json()) ]);我想让它动态化,像这样发出 N 个获取请求: let promiseList = []; try { for (let url of requestUrls) { promiseList.push(fetch(url).then((response) => response.json())); } var data = await Promise.all(promiseList);但我得到这个错误Uncaught SyntaxError: await is only valid in async function的await Promise.all()路线,如果我删除的await,我得到一个Promise {<pending>}和 (index):79 error:TypeError: data is not iterable这是我的完整代码:https : //jsfiddle.net/ham7g82e/1/从这些提取中获取数据我缺少什么?
3 回答

皈依舞
TA贡献1851条经验 获得超3个赞
不要使用 await,而是使用 Promise.then
Promise.all(promiseList).then(data => {
document.getElementById("result").innerHTML = data;
console.log(data);
for (var i of data) {
console.log(`RESPONSE ITEM \n`);
for (var obj of i) {
console.log(obj);
}
}
});

慕村225694
TA贡献1880条经验 获得超4个赞
要使用 await,它需要是异步函数的一部分。
async function functionName() {
//You can use await in here, because you used the async keyword
}
添加回答
举报
0/150
提交
取消