关于这个问题,我不确定这是否可以实现。
我正在使用带有express.js和MySQL数据库的node.js。
我在MySQL数据库里有几条记录。这些记录正在继续更新。
因此,假设我从MySQL获取一些记录,并使用返回为promise的demoFunction函数使用Promise.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);
})发布于 2019-04-28 20:31:45
在此函数中,我尝试检查MySQL数据库中的新记录。如果我有新的记录,那么我想把这个新记录的操作推到当前的Promise.all队列中。这个是可能的吗?
不,Promise.all接受有限数量的承诺,并等待所有承诺的完成。
如果不可能,那么我如何通过继续执行来实现这个目标?
嗯,承诺只是一个值-如果你对某件事有承诺,那么执行已经在其他地方开始了。您总是可以执行第二个.all,但是如果在此期间添加了记录,会发生什么呢?
这样做很好:
Promise.all(allPromises).then(() => Promise.all(allPromises)).then(() => {
});但是在这一点上,您最好在调用Promise.all之前等待checkNewData调用完成,否则您将在checkAllData和Promise.all之间引入一场竞赛
promise是“一次性”的东西,如果你想处理结果,可以考虑使用异步迭代器(注意,这需要Node 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
}
})();https://stackoverflow.com/questions/55890228
复制相似问题