我正在为正在构建的React应用创建进度条,我想将进度条发回给客户的百分比。在快递中,我有API设置,可以解决一系列承诺。我想计算已解决的承诺,并发现以下函数可以跟踪已解决的承诺。
function allProgress(proms, progress_cb) {
let d = 0;
progress_cb(0);
for (const p of proms) {
p.then(() => {
d++;
progress_cb((d * 100) / proms.length);
});
}
return Promise.all(proms);
}
然后我想将我的诺言数组包装在该函数中,然后发送回已解决的诺言百分比,以便我可以建立进度指示器。
app.post('/api/v1/posts', async (req, res) => {
try {
const postData = req.body.postData;
const results = await allProgress(getPostsArray(postData), (p) => {
// I want to send back the percentage in this callback
console.log(p);
res.write(`${p}`);
})
res.send([].concat(...results))
} catch (error) {
console.log(error);
}
})
当我尝试在回调中使用res.write时,似乎失败了。这是在我的回调中使用res.write的正确方法。