0

I have a function that calls from a Promise. The mainFunc() supposes to return the value true. However, It always is a promise.

function mainFunc(){  
  var test = promiseFunc().then(function(result){
    return result;
  })
  alert(test); // should be true value
  return test;
}

function promiseFunc(){
  return new Promise(function(resolve, reject){
    alert(1);
    resolve(true);
  })
}

mainFunc();

Do you know how to return the value from a Promise function in the right way?

You can take a look at the code here: https://jsfiddle.net/vxtmumqz/6/

Thanks,

Dale Nguyen
  • 1,930
  • 3
  • 24
  • 37
  • 1
    Imagine a coffee machine. You put a cup under it. You start the machine. You look into the cup. It is indeed still empty. The machine starts working. The coffee is done. Now you can look at it again and see the coffee. However there is no way to get the coffee before the machine run. – Jonas Wilms Feb 14 '18 at 20:55
  • It sounds quite true about the coffee and the machine. I still don't understand how the value can't be returned from the main function. I should read the other duplicate question then. – Dale Nguyen Feb 14 '18 at 21:06
  • definetly. You cant read a value (the coffee) synchronously, but you need to wait asynchronously until the Promise (the machine) is done – Jonas Wilms Feb 14 '18 at 21:07

1 Answers1

0

see example below...

new Promise(function(resolve, reject) {
    // A mock async action using setTimeout
    setTimeout(function() { resolve(10); }, 3000);
})
.then(function(result) {
    console.log(result);
});
Vitaly Menchikovsky
  • 7,684
  • 17
  • 57
  • 89