简体   繁体   中英

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.

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 ? Do I have to wrap it in an object?

await can only be used inside an async function.

Option 1: invoke an async anonymous function

...

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

Option 2: use promise API (then)

...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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