如何在while循环中串联诺言

时间:2019-06-01 00:53:25

标签: javascript node.js promise cloudant

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

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

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);
            }
        })
    };

基本上,假设输出是日期范围之间所有文档的数组。现在,单个日期有效,但是当我执行一系列日期操作时,请求没有通过,或者我达到了极限,或者说承诺从未解决。我认为这可能不是解决此问题的最佳方法,并且可以接受任何解决方案。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

您的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时,请确保放置{之后{1}}。

答案 1 :(得分:0)

我还没有完全理解您的代码。但是,如果查询彼此独立,则Promise.all()似乎可以解决您的问题:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

如果您实际上需要按同步顺序运行诺言,请尝试简单地等待循环中的诺言解析。