简体   繁体   English

JS:从异步 function 返回 promise 而不解析 promise?

[英]JS: return promise from an async function without resolving the promise?

I'm pretty sure this isn't possible, but asking just in case.我很确定这是不可能的,但以防万一。

Let's say I have a bunch of functions that add to a query builder:假设我有一堆添加到查询构建器的函数:

let query = User.query();
query = filterName(query, name);
query = filterLocation(query, location);
const users = await query;

This is fine.这可以。 However, if I need one of these functions to be async (eg to fetch some data), I can't await the function because it'll resolve the whole query.但是,如果我需要这些函数之一是异步的(例如,获取一些数据),我不能await function 因为它会解决整个查询。

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

Is there a way to make JS not resolve the promise returned by filterLocation ?有没有办法让 JS 无法解析 filterLocation 返回的filterLocation Do I have to wrap it in an object?我是否必须将其包装在 object 中?

await can only be used inside an async function. await只能在async function 中使用。

Option 1: invoke an async anonymous function选项 1:调用异步匿名 function

...

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

Option 2: use promise API (then)选项2:使用promise API(然后)

...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM