gpt4 book ai didi

javascript - JS : elegant way to wait for callbacks to finish

转载 作者:搜寻专家 更新时间:2023-10-31 23:08:02 25 4
gpt4 key购买 nike

在我的 Node 应用程序中,我需要生成多个文件写入并等待它们完成,然后再继续进行其他操作。我通过以下方式实现了这一点:

let counter = 0;
(some loop declaration) {
// (preparing data etc)
counter += 1;
fs.writeFile(fname, fdata, (err) => {
counter -= 1;
});
}
let waitForCallbacks = function() {
if (fcounter > 0) {
setTimeout(waitForCallbacks, 0);
}
};
waitForCallbacks();

虽然它按预期工作,但我觉得可能有一些更好的习惯用法。有什么建议吗?

最佳答案

While it works as desired, I feel that there could be some nicer idiom for that.

这是 promises 的设计目的之一。这是用 promises 重写的代码(它可以更进一步,有一些库可以 promise-ify NodeJS API):

let operations = []
(some loop declaration) {
// (preparing data etc)
operations.push(new Promise((resolve, reject) => {
fs.writeFile(fname, fdata, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
}));
}
Promise.all(operations).then(() => {
// All done
});

或者考虑一下我们是否有 writeFile 的 promise 化版本:

let operations = []
(some loop declaration) {
// (preparing data etc)
operations.push(writeFileWithPromise(fname, fdata));
}
Promise.all(operations).then(() => {
// All done
});

或者如果“循环”遍历一个可迭代对象,我们可以将其转换为数组并在以下位置使用 map:

Promise.all(
Array.from(theThingy).map(entry => writeFileWithPromise(entry.fname, entry.fdata))
).then(() => {
// All done
});

关于javascript - JS : elegant way to wait for callbacks to finish,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39500344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com