在 promise.all 运行时添加到节点中



我不确定这个问题是否可以实现。

我正在使用node.js与express.js和MySQL数据库。

我在MySQL数据库中有一些记录。这些记录正在继续更新。

因此,假设我从 MySQL 获取一些记录并使用返回 promise 的函数demoFunctionPromise.all对每条记录进行操作。

在此函数中,我正在尝试检查MySQL数据库中的新记录。如果我有新记录,那么我想将此新记录的操作推送到当前Promise.all队列中。这可能吗?如果不可能,那么我如何通过继续执行来实现这一目标?

所以,我的代码是这样的,

const demoFunction = (arg1, arg2) => {
checkForNewData();
return new Promise((resolve, reject) => {
// Rest of my code is here for this function
// This function will be take around 5 to 10 mins    
});
};
const dataFromDatabase = "Here i'm getting some data into array of object from SQL database";
let allPromises = dataFromDatabase.map((obj) => demoFunction(obj.arg1, obj.arg1));
const checkForNewData = () => {
const newDataFromDatabase = "Here i'm getting some new data into array of object from SQL database";
for (let i = 0; i < newDataFromDatabase.length; i++) {
allPromises.push(demoFunction(newDataFromDatabase[i].arg1, newDataFromDatabase[i].arg2));
}
};
return Promise.all(allPromises)
.then(() => {
// response
})
.catch((e) => {
console.log(e);
})

在此函数中,我正在尝试检查MySQL数据库中的新记录。如果我有新记录,那么我想把这个新记录的操作推送到当前的 Promise.all 队列中。这可能吗?

不,Promise.all接受有限且设定数量的承诺,并等待所有承诺完成。

如果不可能,那么我如何通过继续执行来实现这一目标?

好吧,承诺只是一个价值——如果你对某事有一个承诺,那么执行已经在其他地方开始了。您始终可以执行第二个.all但是如果同时添加了记录,会发生什么情况?

可以做:

Promise.all(allPromises).then(() => Promise.all(allPromises)).then(() => {
});

但是在这一点上,你最好在调用Promise.all之前等待checkNewData调用完成,否则你就会在checkAllData和Promise.all之间引入一场竞赛。


承诺是"一次性"的事情,如果你想处理结果,请考虑使用异步迭代器(注意,这需要节点 12):

async function* getRecordData() {
for await(const item in getPromisesOfInitDataFromDatabase()) {
yield item; // or process it
}
while(true) { // or how often you want
for await(const item of getNewDastaFromDatabase()) {
yield item; // or process it
}
await sleep(3000); // or some sleep timeout to not constantly poll
}
} 

然后在其他地方:

(async () => {
for await(const item of getRecordData()) {
// items are available here one by one, including new items in the database
}
})();

最新更新