使用异步函数和承诺处理递归的最佳方法?
Best way to handle recursion with async functions and promises?
以下是说明我的问题的伪代码。当所有任务完成时,父函数最终必须 return 一个承诺(为清楚起见,我省略了其他任务)。父函数调用子函数,一些子函数必须递归地执行它们的任务,因此,为了清楚起见,我将它们分成辅助函数。如果有更简洁的方法我很想学习。
如何最好地处理此示例中的递归?
// This function must ultimately return a Promise.
async function parentFunction(uId) {
try {
await childFunction(uId);
return Promise.resolve(uId);
} catch (error) {
console.log(error);
}
}
async function childFunction(uId) {
try {
const done = await workerFunction(uId);
if (done) {
return Promise.resolve(true);
} else {
// There are more files to delete; best way to handle recursion?
}
} catch (error) {
console.log(error);
}
}
async function workerFunction(uId) {
try {
// Query the database, limit to 100 files.
const query = await db.queryFiles().limit(100);
if (query.size == 0) {
// Nothing to delete, we're done!
return Promise.resolve(true);
}
// Perform an atomic (all-or-none) batch delete that can only take 100 files at most.
await db.batchDelete(query);
// Batch delete successfull!
if (query.size < 100) {
// The query was less than 100 files so there can be no more files to delete.
return Promise.resolve(true);
} else {
// There may possibly be more files to delete.
// Return a promise or handle recursion here?
return Promise.resolve(false);
}
} catch (error) {
console.log(error);
}
}
递归就行了!
async function deleteFiles() {
const query = await db.queryFiles().limit(100)
if (query.size > 0) {
await db.batchDelete(query)
}
if (query.size === 100) {
return deleteFiles()
}
return true;
}
以下是说明我的问题的伪代码。当所有任务完成时,父函数最终必须 return 一个承诺(为清楚起见,我省略了其他任务)。父函数调用子函数,一些子函数必须递归地执行它们的任务,因此,为了清楚起见,我将它们分成辅助函数。如果有更简洁的方法我很想学习。
如何最好地处理此示例中的递归?
// This function must ultimately return a Promise.
async function parentFunction(uId) {
try {
await childFunction(uId);
return Promise.resolve(uId);
} catch (error) {
console.log(error);
}
}
async function childFunction(uId) {
try {
const done = await workerFunction(uId);
if (done) {
return Promise.resolve(true);
} else {
// There are more files to delete; best way to handle recursion?
}
} catch (error) {
console.log(error);
}
}
async function workerFunction(uId) {
try {
// Query the database, limit to 100 files.
const query = await db.queryFiles().limit(100);
if (query.size == 0) {
// Nothing to delete, we're done!
return Promise.resolve(true);
}
// Perform an atomic (all-or-none) batch delete that can only take 100 files at most.
await db.batchDelete(query);
// Batch delete successfull!
if (query.size < 100) {
// The query was less than 100 files so there can be no more files to delete.
return Promise.resolve(true);
} else {
// There may possibly be more files to delete.
// Return a promise or handle recursion here?
return Promise.resolve(false);
}
} catch (error) {
console.log(error);
}
}
递归就行了!
async function deleteFiles() {
const query = await db.queryFiles().limit(100)
if (query.size > 0) {
await db.batchDelete(query)
}
if (query.size === 100) {
return deleteFiles()
}
return true;
}