javascript - 如何在 while 循环中串联连接 Promise

标签 javascript node.js promise cloudant

我必须连续查询多个数据库。基本上是一组必须连续完成的 promise 。我正在 while 循环中实现它。数据库根据日期命名。我还必须将请求延迟设置为 400 毫秒乘以每个 Promise 之间传递的循环量 (400*count)。如果有帮助的话,我将使用 cloudant 作为我的数据库,类似于 mongodb/couchdb,但是是一个在线实例。

因此,我实现了一个查询函数,该函数将获取开始日期和结束日期,并检索该范围内的所有值。如果日期相同,则它将查询一个数据库,否则它将针对日期范围之间的每一天查询多个数据库。我主要在 if 语句中的 else block 上遇到问题,如下所示。

db.predQuery = (start, end, locationCode) => {
        return new Promise((resolve, reject) => {
            let data = [];
            const startDate = moment(start, "MM/DD/YYYY");
            const endDate = moment(end, "MM/DD/YYYY");
            if (startDate.diff(endDate) === 0) {
                // THIS IF BLOCK WORKS GOOD
                let dbName = `prediction_${String(locationCode)}_`;
                dbName += startDate.format("YYYY-MM-DD");
                const db = this.cloudant.use(dbName);
                return db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                    data = body.docs;
                    return resolve(data);
                });
            } else {
                // THIS BLOCK IS WHERE THE PROBLEM IS

                // This is to start off the promise chain in the while loop
                let chainProm = Promise.resolve(1);
                let iterator = moment(startDate);
                let count = 0;

                // While loop for the series of promises
                while (iterator.isBefore(endDate) || iterator.isSame(endDate)) {
                    //dbName Format: prediction_0_2019-05-28
                    let dbName = `prediction_${String(locationCode)}_`;
                    dbName += iterator.format("YYYY-MM-DD");
                    const db = this.cloudant.use(dbName);
                    count += 1;

                    // Set off chain of promises
                    chainProm = chainProm.then(() => {
                        setTimeout(()=>{
                            db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                                // Keep adding on to the old array
                                data = data.concat(body.docs);
                            });
                        },count*400);
                    });

                    // Move to the next day
                    iterator.add(1,'days');
                }
                // Once all done resolve with the array of all the documents
                return resolve (data);
            }
        })
    };

基本上,输出应该是日期范围内所有文档的数组。现在单个日期有效,但是当我执行一系列日期时,要么请求没有通过,要么我达到限制,或者它说 promise 永远不会得到解决。我认为这可能不是解决这个问题的最佳方法,并且我对任何解决方案持开放态度。非常感谢任何帮助。

最佳答案

您的 chainProm 未与 predQuery 的外部调用连接 - resolve 正在立即调用。

您可能会发现使用 async/await 更容易,循环内延迟逻辑也更容易理解:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
db.predQuery = async (start, end, locationCode) => {
  const startDate = moment(start, "MM/DD/YYYY");
  const endDate = moment(end, "MM/DD/YYYY");
  if (startDate.diff(endDate) === 0) {
    // THIS IF BLOCK WORKS GOOD
    let dbName = `prediction_${String(locationCode)}_`;
    dbName += startDate.format("YYYY-MM-DD");
    const db = this.cloudant.use(dbName);
    const body = await db.find({selector: {_id: {'$gt': 0}}});
    return body.docs;
  }
  const iterator = moment(startDate);
  const data = [];
  const testShouldIterate = () => iterator.isBefore(endDate) || iterator.isSame(endDate);
  let shouldIterate = testShouldIterate();
  while (shouldIterate) {
    //dbName Format: prediction_0_2019-05-28
    let dbName = `prediction_${String(locationCode)}_`;
    dbName += iterator.format("YYYY-MM-DD");
    const db = this.cloudant.use(dbName);
    const body = await db.find({selector: {_id: {'$gt': 0}}});
    data.push(body.docs);
    // Move to the next day
    iterator.add(1,'days');
    shouldIterate = testShouldIterate();
    // Don't delay on the final iteration:
    if (!shouldIterate) {
      break;
    }
    await delay(400);
  }
  // Once all done resolve with the array of all the documents
  return data;
};

通过此实现,任何错误都会发送给 predQuery 的调用者(错误将导致其返回的 Promise 被拒绝),因此在调用 predQuery 时,确保之后放置一个catch

关于javascript - 如何在 while 循环中串联连接 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56403100/

相关文章:

Javascript 无法使用 fetch 捕获错误

javascript - Node.js:确定手动安装的模块和 package.json 的版本号

node.js 在变量中表达 mvc 方法名称

macos - Node.js 在 mac osx 10.8.4 上安装 Canvas 失败 : src/Canvas. h..... fatal error : v8. h 文件未找到

javascript - 未收到来自 Express 服务器的 GET 响应

javascript - Node.js 使用 Promise.all 等待嵌套的 Promise

javascript - 访问 Javascript promise 链中的变量

javascript - Vaadin 应用程序中发出蜂鸣声

javascript - 如何在本地导入Vue/Nuxt.js中的CSS框架?

JavaScript jQuery 提交按钮问题