我想从 do while 循环中调用异步函数,并且仅当该函数不返回值时才退出。 有没有一种方法可以管理这个问题,而不必在回调之外实际等待?
下面的代码显然总是在第一个循环中退出,因为在评估 while () 时函数尚未回调:
var i = 0;
do {
var foundListing;
if (i) {
listing.slug = listing.slug + '-' + (i + 1);
}
listingService.getListingBySlug(listing, function(error, pFoundListing) {
if (error) {
return callback(util.errorParser(error));
} else if (Object.keys(pFoundListing).length) {
foundListing = pFoundListing;
i++;
}
});
//Do I have to wait here???
} while (foundListing && Object.keys(foundListing).length);
澄清: 这里的重点是生成一个独特的 slug。如果 slug 已经存在,我会附加一个数字并再次检查它是否存在。当我找到还不存在的数字时,我就完成了。
更新: 我找到了一种使用递归的方法。我将工作片段发布为 answer .
最佳答案
我无法测试它,但也许递归函数应该可以:
const listingService = {
getListingBySlug(listing, callback) {
setTimeout(() => {
if (listing.slug === 'listing-5') {
callback(
false,
{
name: 'Listing 1',
slug: 'listing-1',
}
);
}
else {
callback(false, {});
}
}, 1000);
},
};
function checkListingExists(slug) {
return new Promise((resolve, reject) => {
const listing = { slug };
listingService.getListingBySlug(listing, (error, pFoundListing) => {
if (error) {
reject(error);
} else if (Object.keys(pFoundListing).length) {
resolve(pFoundListing);
} else {
resolve(false);
}
});
});
}
function nextListing(prefix, index) {
checkListingExists(prefix + '-' + index)
.then((listing) => {
if (listing === false) {
nextListing(prefix, index + 1);
} else {
console.log(listing);
}
})
.catch(() => {
// deal with error response
});
}
nextListing('listing', 0);
关于javascript - Node.js 从 do while 循环中调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41693437/