[我试图遍历数据库中的记录,以便编译将要写入另一个数据库的数组(cardsToInsert)。
我被困住了,因为数组在循环完成之前就已写入数据库,我知道我需要使用promises / async函数来实现我想要的功能,但是我很确定自己的诺言做错了。
该代码适用于几个循环(它大约循环6-10次,应该循环16次),但是随后在尝试wixData.get时挂起(或者挂在buildCard的另一个诺言上) 。
// wixData.get is a function that returns a promise
async function loopCards(cardsToGet) {
let writeCard
let buildCard
for (let index = 0; index < cardsToGet.length; index++) {
const cardToGet = cardsToGet[index].card
buildCard = await wixData.get("Card", cardToGet)
.then((card) => {
return card
})
.catch((err) => {
let errorMsg = err;
return errorMsg
});
writeCard = await buildingCard(buildCard)
cardsToInsert.push(writeCard)
}
return cardsToInsert
}
我做错了什么? (或者我做错的关键是要停止这项工作,我敢肯定,这里还有很多地方可以改进!)
UPDATE
我现在已经更新了代码,并且可以正常循环。
async function loopCards(cardsToGet) {
console.log('Start')
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;
return errorMsg
});
}
return cardsToInsert
}
在最终返回cardsToInsert之前,如何等待循环完成?
async/await
和.then
的组合不是真正的最佳实践
这应该起作用,并且在cardsToInsert被填充后将返回
async function loopCards(cardsToGet) {
const cardsToInsert = [];
for (let cardToGet of cardsToGet) {
try {
const card = await wixData.get("Card", cardToGet);
const writeCard = await buildingCard(card);
cardsToInsert.push(writeCard);
}
catch(err) {
let errorMsg = err;
return errorMsg;
}
}
return cardsToInsert;
}
更好的是,您真的不需要在这里处理任何错误,因为调用函数可以做到这一点
因此变得更加简单
async function loopCards(cardsToGet) {
const cardsToInsert = [];
for (let cardToGet of cardsToGet) {
const card = await wixData.get("Card", cardToGet);
const writeCard = await buildingCard(card);
cardsToInsert.push(writeCard);
}
return cardsToInsert;
}
然后使用它可能是
loopCards(cards)
.then(result => doSomethingWihtResult)
.catch(error => handleError);
或如果从异步函数调用
try {
let result = await loopCards(cards);
// do something with result
} catch(error) {
// handle Error
}