【问题标题】:Add new function in promise.all runtime in node在 node 的 promise.all 运行时添加新函数
【发布时间】:2019-04-28 20:31:45
【问题描述】:

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

我将 node.js 与 express.js 和 MySQL 数据库一起使用。

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

所以,假设我从 MySQL 获取一些记录,并使用返回 promise 的 demoFunction 函数对每条记录进行操作。

在这个函数中,我试图检查 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);
    })

【问题讨论】:

  • dataFromDatabasenewDataFromDatabase 是什么?承诺?

标签: asynchronous promise async-await synchronous


【解决方案1】:

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

不,Promise.all 接受有限数量的 Promise 并等待它们全部完成。

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

嗯,promise 只是一个值——如果你对某事有一个 promise,那么执行已经在其他地方开始了。您始终可以执行第二个.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
  }
})();

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 2021-07-22
    • 1970-01-01
    • 2016-04-03
    • 2018-09-19
    • 1970-01-01
    相关资源
    最近更新 更多