【问题标题】:write a while loop using promises using return values within the next promise在下一个 Promise 中使用返回值使用 Promise 编写一个 while 循环
【发布时间】:2020-01-09 07:56:49
【问题描述】:

我已经阅读了关于这个主题的所有关于 SO 的问题,但我仍然陷入困境,因为 promiseWhile 中的 condition 函数不带参数。

我的用例如下。我正在尝试查询某个日期的一些信息(start_date)。我不知道我的数据库中是否有start_date 的信息,所以我想检查一下。如果没有数据,我想在前一天查询并继续这样做,直到有数据为止。 (我知道promise while loop 不是最好的方法,但我还是想学习如何做到这一点)

这是我目前的代码

let start_date = DateTime.fromFormat(req.body.date, "yyyy-MM-dd");
let date_promise = (the_date) => {
    let the_req = {
        date: the_date
    };
    return db.query(the_req);
};

let promiseWhile = Promise.method(function (condition, action) {
    if (!condition()) return;
    return action().then(promiseWhile.bind(null, condition, action));
});

promiseWhile(
    (body) => {return body.rows.length > 0},
    () => {
        start_date = start_date.minus(luxon.Duration.fromObject({days: 1}))
        return date_promise(start_date);
    },
).then((result) => {
    // start_date ... 
    // do something with the date I've obtained
});

date_promise 返回一个承诺。

在我的promiseWhile 条件下,我试图测试body.rows 是否包含body.then 函数的参数,在date_promise 的结果解析后。 (date_promise(some_date).then((body) => {...}))。

我不知道如何从那里开始。欢迎任何帮助。

【问题讨论】:

  • 我看到的前 2 个问题是 a) 在您的情况下,您说该函数有一个 body 参数,但在 promiseWhile 中,您调用了没有参数的 condition 函数。 b) 在action().then(promiseWhile(...)) 上,您的语法错误。尝试将其更改为action().then(() => promiseWhile(...))
  • 感谢您抽出宝贵的时间。是的 a) 正是我的问题。你如何编写一个带参数的condition 函数?

标签: javascript promise es6-promise bluebird request-promise


【解决方案1】:

Promise.method 是 async functions 的旧版本。考虑到这一点并进行一些语法更正,您的代码将如下所示:

let start_date = DateTime.fromFormat(req.body.date, "yyyy-MM-dd");

let date_promise = (the_date) => {
    let the_req = {
        date: the_date
    };
    return db.query(the_req);
};

const myAction = date => () => date_promise(date);

let promiseWhile = async function (condition, action) {
    const queryResults = await action();
    if (!condition(queryResults)) {
      start_date = start_date.minus(luxon.Duration.fromObject({days: 1}));
      return promiseWhile(condition, myAction(start_date));
    } else {
      return queryResults;
    }
};

promiseWhile(
    body => body.rows.length > 0,
    () => {
        return myAction(start_date);
    },
).then(result => { // The result you'll get here is queryResults.
    // start_date ... 
    // do something with the date I've obtained
});

【讨论】:

  • 如何让body(在promiseWhile 内)成为date_promise().then(..) 的结果?
  • 我编辑了这个问题来回忆 promiseWhile 每次都有一个新的日期。请告诉我进展如何。
  • 现在尝试感谢您的时间。为什么你创建了一个currentDate 变量而不是直接使用start_datemyAction 也正是 date_promise 不是吗?你为什么要创建一个新函数?
  • 好的,它可以工作。伟大的。我唯一修改的是 1. 我没有使用 currentDate 变量和 2. myAction 应该返回一个函数,所以我使用了const myAction = (date) => { return () => date_promise(date); };
  • 您能否修改您的答案以包含这些内容,我会验证。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 2019-09-17
  • 1970-01-01
  • 2021-09-07
  • 2014-10-21
  • 2020-11-28
  • 1970-01-01
相关资源
最近更新 更多