[英]How to return array at end of loop (Newbie question)
下面的代码(为了清楚起见,我已经简化了)循环并在循环的每个部分完成之前返回cardsToInsert,因此无法正确构建数组。
循环正确地构建了数组,但结果在开始时返回,而不是在构建之后。
如何让它在返回数组之前完成所有循环?
async function loopCards(cardsToGet) {
for (let cardToGet of cardsToGet) {
getDataFunctionWhichReturnsAPromise()
.then(async (card) => {
writeCard = await buildingCard(card)
cardsToInsert.push(writeCard)
}
return cardsToInsert
}
谢谢
按要求添加完整代码
// wixData.get() 返回一个 promise
async function loopCards(cardsToGet) {
let writeCard
let buildCard
for (let index = 0; index < cardsToGet.length; index++) {
const cardToGet = cardsToGet[index].card
buildCard = wixData.get("Card", cardToGet)
.then(async (card) => {
writeCard = await buildingCard(card)
cardsToInsert.push(writeCard)
}
)
.catch((err) => {
let errorMsg = err;
console.log("getcard error: " + errorMsg);
return errorMsg
});
}
return cardsToInsert
}
你应该用 promise.then 包裹循环,或者你也使用异步它的意思是数组的第一项将被打印,然后它会等待
getDataFunctionWhichReturnsAPromise()
.then(async (card) => {
for (let cardToGet of cardsToGet) {
writeCard = await buildingCard(card)
cardsToInsert.push(writeCard)}
}
这里有详细的解释
要从 Promise 中获取数据,您需要使用回调、async-await 或 promise 等待它完成。
在您的代码中,您将.then
用于访问 wixData 的结果,但整个wixData.get("Card", cardToGet).then(async (card) => {})
是用于loopCards(cardsToGet)
的异步 function 和因此,您的循环完成并且结果数组为空。
解决方案 - 只需等待wixData.get("Card", cardToGet)
完成,然后进行操作。 这是使用异步等待的解决方案。
async function loopCards(cardsToGet) {
let cardsToInsert = [];
for (let index = 0; index < cardsToGet.length; index++) {
const cardToGet = cardsToGet[index].card
let card = await wixData.get("Card", cardToGet)
let writeCard = await buildingCard(card)
cardsToInsert.push(writeCard)
}
return cardsToInsert
}
在上面的代码中,我等待wixData.get("Card", cardToGet)
完成并将结果存储在 get card 中。 这应该可以解决您的问题。
但是这个代码的性能并不是最优的,因为你正在等待每个网络调用。 您可以做的是使用 Promise.all 一次执行所有承诺
这是带有错误处理的代码 -
async function loopCards(cardsToGet){
try {
return await Promise.all( cardsToGet.map( cardToGet => buildCard( cardToGet.card )));
}
catch (error) {
console.log(error);
}
}
async function buildCard(cardToGet){
try {
let card = await wixData.get("Card", cardToGet);
let writeCard = await buildingCard(card);
return writeCard;
}
catch (error) {
console.log("getcard error: " + error);
return error;
}
}
上面的代码可能有一些错误,因为我还没有测试过,但我希望你能得到这个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.