我已经阅读了有关此主题的所有问题,但由于condition
中的promiseWhile
函数没有参数,因此我仍然很困惑。
我的用例如下。我正在尝试查询某个日期的某些信息(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) => {...})
)。
我不确定如何从那里继续。欢迎任何帮助。
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);
};
let promiseWhile = async function (condition, action) {
if (!condition(body)) return;
await action();
promiseWhile.bind(null, condition, action);
};
promiseWhile(
body => 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
});
我不确定这是否可以解决您的问题,但这只是一个开始。请让我知道它的进展。