我正在尝试从嵌套的 for 循环中解析 promise:
let fillInTable = () => {
let result = []
$.getJSON(`https://kvdb.io/${bucket}/?format=json`).then((data) => {
data.map(each => $.getJSON(`https://kvdb.io/${bucket}/${each}`).then(o => {
result.push(o)
}));
});
return result
}
let random = fillInTable(); // appears to be []
// TODO: Wait for random to receive all the information from fillInTable() before executing anything else
将random
永远是空的,我猜在默认情况下getJSON
是异步。我正在尝试使用await
但它不起作用,因为它不在异步函数中。
我试图将所有承诺推送到一个数组中,然后使用Promise.all([...])
但也不起作用。
有没有人有办法解决吗?
我已经用一些虚拟的 JSON 端点替换了这两个 URL,以使其工作。它也应该与您自己的端点一起使用。
let fillInTable = async () => {
let data = await $.getJSON(`https://api.myjson.com/bins/awyt4`);
let result = await Promise.all(
data.map( each => $.getJSON(`https://jsonplaceholder.typicode.com/posts?id=${each}`) )
);
return result
}
fillInTable()
.then( random => console.log( random ));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句