-1

I can't find my mistake in the following code. All I want is save() to return true or false but its always undefined

function mypromise() {
  return new Promise((resolve, reject) => {
    resolve("it worked")
  })
}

function save() {
  mypromise().then(success => {
    return true
  }, error => {
    return false
  });
}

var saveSuccessful = save();
console.log('success', saveSuccessful) // undefined ?
Hedge
  • 16,142
  • 42
  • 141
  • 246
  • code inside your callbacks is executed asynchronously. – madox2 Jan 09 '16 at 21:03
  • Your function `save()` does not return anything - what did you expect? – Benjamin Gruenbaum Jan 09 '16 at 21:05
  • @BenjaminGruenbaum When I do `save mypromise().then()` I get the pending Promise back. Is there a way to return the value directly? – Hedge Jan 09 '16 at 21:07
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Amit Jan 09 '16 at 21:44
  • Your `save` function returns nothing. Please make sure, don't missed to return promise out of here. Then you should use `.then` to check whether save was success or not – just-boris Jan 10 '16 at 12:14

1 Answers1

0

You'll know if the save is successful only when the promise has finished executing, like so:

function mypromise() {
  return new Promise((resolve, reject) => {
    resolve("it worked")
  })
}

function save() {
  mypromise().then(success => {
    console.log('success');
    return true;
  }, error => {
    return false
  });
}

save();

If you could write var saveSuccessful = save(); that would mean that save() is synchronous, by definition of synchronous, but you explicitely want it to be asynchronous.

Ilya
  • 5,377
  • 2
  • 18
  • 33
  • And see http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call for more details. – Ilya Jan 09 '16 at 23:17