JS:从异步函数返回承诺而不解决承诺?

时间:2021-04-21 08:52:07

标签: javascript node.js async-await

我很确定这是不可能的,但以防万一。

假设我有一堆添加到查询构建器的函数:

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?我必须将它包装在一个对象中吗?

1 个答案:

答案 0 :(得分:-4)

await 只能在 async 函数内使用。

选项 1:调用异步匿名函数

...

(async function(){
   query = await filterLocation(query, location);
})();

选项 2:使用 promise API(当时)

...

filterLocation(query, location)
    .then(function (query){
       ...
    });