【发布时间】:2021-04-21 17:06:15
【问题描述】:
我很确定这是不可能的,但以防万一。
假设我有一堆添加到查询构建器的函数:
let query = User.query();
query = filterName(query, name);
query = filterLocation(query, location);
const users = await query;
这很好。但是,如果我需要这些函数之一是异步的(例如,获取一些数据),我不能 await 该函数,因为它会解析整个查询。
async function filterLocation(query, location) {
const data = await ...;
return query.where(...);
}
...
query = await filterLocation(query, location); // `query` is now resolved to a list of users, but I want it to remain a promise
有没有办法让JS不解析filterLocation返回的promise?我必须将它包装在一个对象中吗?
【问题讨论】:
-
如果您只想要承诺,无需等待它解决,请执行以下操作:
queryPromise = filterLocation(query, location)。是这个意思吗? -
承诺立即开始,一旦你做了
= User.query(),它就已经开始了。现在添加东西已经太晚了。您需要的是最后一行的await query.exec()之类的东西,它将开始实际工作。所以是的,你必须把它包起来。 -
await 实际上并没有解决任何问题,它(递归地)解开 promise 以获取其底层值。
-
@georg 我正在使用 knex,它允许我以问题中的方式使用它。我假设他们有
setTimeout(, 0)允许修改查询 -
@IAmDranged 如果您更喜欢“解包”而不是“解决”,那么问题将是“您能否在不解包承诺的情况下从异步函数返回承诺?”
标签: javascript node.js async-await