简体   繁体   中英

Return a non-resolved promise from a promise

find is a function that returns a promise that resolves to a value, but also has data on the promise object itself. A practical use case is when find() returns a dbQueryObject that can be used elsewhere, whereas await find() resolves with databaseResults. eg:

function find () {
  var results = new Promise(/* resolves with databaseResults */)
  Object.assign(results, new dbQueryClass)
  return results
}

I can wrap find with a function to provide helpers like this,

function findPage (page) {
 return find().skip(page*20).limit(20)
}

and use it like findPage().select('_id') to get the query object or await findPage().select('_id') to get the resolved value (returns something similar to find() ).

However, if I wrap find with a promise like this,

async function findSomething() {
  var someArgs = await promise1()
  if (someArgs) return find(someArgs)
  return find()
}

How do I get the value of find() itself outside of findSomething ? I need promise1 to resolve, but I need find() to not resolve. find() is a plain object AND a thenable, depending on if you resolve it or not, but resolving findSomething() will automatically resolve the returned value. How do I return it such that it doesn't resolve?

My constraint is that I cannot modify the library that provides find() to not return a thenable object.

I don't see what would "usually" be an antipattern here. You can return or await any promise, thenable or plain value in an async function, just as you can Promise.resolve them or return them from a then callback. There is nothing unusual about this, that's just how it is done.

If you want to be explicit about returning a promise, instead of relying on thenable assimilation, you can always call .exec() on your mongoose query and it will get you a "real" promise.

As stated here https://stackoverflow.com/a/22724984/704894 , it's impossible to have Promise<Promise<value>> because when you return a Promise inside .then handler, it gets automatically resolved (unwrapped).

You'd have to use Promise<Wrapper<Promise>> to bypass this limitation.

Sidenote for functional programming folks: .then is both map and flatMap in Haskell terms.

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