简体   繁体   中英

Returning a result from a function after a promise resolves

So I have to pass a simple boolean to a library. In order to get the value to return I have to evaluate the resolution of a promise(it makes a asynchronous call). So I have something like this:

import {funcThatReturnsPromise} from 'some-module';

function someFunc(someParam) {
   funcThatReturnsPromise(someParam).then(theResult => someOtherFunc(theResult));
} 

function someOtherFunc(someParam) {
   ....
   return true; // do some things and return a bool
}

The problem is that this returns a promise, not the bool. I can't (without forking a third party project) modify the calling code to handle a promise rather than a bool. I know the whole point of promises is to be able to handle asynchronous calls without nesting but in this case I need to handle things synchronously. I'm not sure how to do that. I've looked through the docs but I'm not seeing a way to do this. Could anyone point me in the right direction here?

Dealing with promises and asynchronous code can be confusing, but the key is to not overcomplicate it. Don't try to un-invent the wheel, try to understand where your code belongs within this structure.

If you want a section of code to run after the resolution of the promise, then it belongs in the .then callback. It sounds like you have half of your code in and half of your code out of that callback.

Expanding your code a little, I'm assuming you're trying to do something to the effect of;

function someFunc(someParam) {
   funcThatReturnsPromise(someParam).then(theResult => someOtherFunc(theResult));

   if(someOtherFunc(theResult)){
       alert('A RESULT!');
   }
} 

function someOtherFunc(someParam) {
   ....
   return true;
}

But what you should be doing is;

function someFunc(someParam) {
   funcThatReturnsPromise(someParam).then(theResult => {
       funcResult = someOtherFunc(theResult)
       if(funcResult){
           alert('A RESULT!')
       }
   });

} 

function someOtherFunc(someParam) {
   ....
   return true;
}

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