-1

Here is a function that I would like to call for its return value, and in that function I would like to use an async call that would set a flag to work with later on:

function getSomething() {
    var isOk;

    myAsyncFunction(function(data) {
        if (data === 'foo') {
            isOk = true;
        }
    });

    //...

    if (isOk) {
        return true;
    }
}

I would want to use getSomething() like this:

if (getSomething()) {...}

I know that it won't pause the execution of this function to wait for my async call to finish. I also know that the return true statement should not be in the callback of the async function. But how can I wait for the async function's callback? Should I transform my getSomething() call to a promise or is there another way? And how would be the call of getSomething() look like if I'd use promises? Thanks in advance!

Lgn
  • 9,581
  • 5
  • 20
  • 26
  • `myAsyncFunction` should return a promise, you should return that promise from `getSomething`. – Kevin B Sep 16 '15 at 18:08
  • *"But how can I wait for the async function's callback?"* you can't, that isn't possible. The only option is to use callbacks, either directly or on promise objects. – Kevin B Sep 16 '15 at 18:09

1 Answers1

0

You can use JavaScriptPromise

var promise = new Promise(function(resolve, reject) {


  if (/* everything turned out fine */) {
    resolve("worked!");
  }
  else {
    reject(Error("broke"));
  }
});

How to use

promise.then(function(result) {
  console.log(result); // "worked!"
}, function(err) {
  console.log(err); // Error: "broke"
});

For more information you can visit this link Promise

santosh singh
  • 27,666
  • 26
  • 83
  • 129
  • 2
    But you still can't use the return value in an `if`. You can't **wait** for asynchronous actions. – Barmar Sep 16 '15 at 18:23