【发布时间】: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