-1

I want to do this:

function save() {
  //does some stuff here

  somePromise.then(x => {
    //do some stuff here
  }).then(z => {
    //return statement that makes you leave the function
  })
}

I have a function and I want to have a return that will finish its execution inside a then because I'm working with promises.

Any help or advice will be greatly appreciated. Thanks in advance.

alexmac
  • 19,087
  • 7
  • 58
  • 69
  • What's the purpose of this? Are using the return to leave the function early? – evolutionxbox Sep 29 '17 at 18:00
  • Do you want to return from `save` function? – alexmac Sep 29 '17 at 18:00
  • My advice, seen as your using promises, use async / await.. – Keith Sep 29 '17 at 18:00
  • There no notion of "leaving a function". And promise callbacks can only execute async anyway. It sounds like you actually want to return your promise chain. – SLaks Sep 29 '17 at 18:01
  • I want to leave the function earlier in case an error occurs. –  Sep 29 '17 at 18:05
  • @D.Tex: At that point, there is no function to leave. You need to understand how async and promises work. – SLaks Sep 29 '17 at 18:06
  • `case an error occurs.` Then throw an error, that's the whole point of promises compared to callbacks, there is built in error handling. – Keith Sep 29 '17 at 18:07
  • Okay, I'll elaborate better my case... I have function that gives the element that triggers the save button an attribute that toggles a modal, but it only works if I leave the function before it's finished hence why I need the return there... without the return it isn't working whereas with return it works... outside of the promise, of course... –  Sep 29 '17 at 18:10
  • @D.Tex Can you include the actual code used and the expected result at Question? See https://stackoverflow.com/help/mcve – guest271314 Sep 29 '17 at 18:18
  • The function `save()` was long since exited before the very first `savePromise.then()` handler ever executed. So, what you want to have happen inside the `.then()` handler has already happened. That's because all `.then()` handlers are async and executed on future ticks. Meanwhile, your `save()` function has already finished and returned. Probably what you need to do is to do return `savePromise.then().then()`. Then the caller to `save()` can use the returned promise to know when everything is done. Async in Javascript is non-blocking. `save()` won't "wait" for async things to be done. – jfriend00 Sep 29 '17 at 18:42

4 Answers4

1

Use return

function save() {
  //does some stuff here

  return somePromise.then(x => {
    //do some stuff here
    return /* value */
  }).then(z => {
    //return statement that makes you leave the function
    return /* value */
  })
}
guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    Not sure why this was downvoted, OP's question is poorly phrased but if I had to bet on an answer that would be it, – Benjamin Gruenbaum Sep 29 '17 at 18:03
  • @BenjaminGruenbaum Would have previously asked what the reason was for "downvote", in order to improve or delete Answer; though SO explicitly encourages "downvote" without a valid reason https://meta.stackoverflow.com/questions/356706/moderator-deleting-comments-by-op – guest271314 Sep 29 '17 at 18:04
  • I never down-voted,. But I kind of interpreted it as been able to conditionally return from a promise chain. This will always return.. – Keith Sep 29 '17 at 18:05
  • @Keith Yes, first `return` a value from the function call, then `return` a value from `.then()`. The code at Question does not return a value at all from `save()` function call, see also [Why is value undefined at .then() chained to Promise?](https://stackoverflow.com/questions/44439596/why-is-value-undefined-at-then-chained-to-promise) – guest271314 Sep 29 '17 at 18:07
0

Ok, seen as your using promises. One of the best features to work with promises is async / await, most modern browsers even have this now built in, if you need to target older browsers you can use something like babel.

The nice thing is you can continue to use Javascript with async code,as if it was sync, including for loops / returns / breaks.. etc..

example below..

async function somePromise() {
  console.log('Some promise called');
}

async function earlyReturnTest(doEarly) {
  await somePromise();
  if (doEarly) return;
  console.log('Return not called');
}

async function run() {
  console.log('Without return');
  await earlyReturnTest(false);
  console.log('');
  console.log('With return');
  await earlyReturnTest(true);
}

run();
Keith
  • 22,005
  • 2
  • 27
  • 44
-1

The problem is that you will have already left the save() function before your then() runs. It does not wait on it. One solution might be to have your save take a callback function as a parameter so you can call back to the code that is waiting.

function save(callBack) {
  //does some stuff here

  somePromise.then(x => {
    //do some stuff here
  }).then(z => {
    //return statement that makes you leave the function
    callBack();
  })
}

// example of code calling the save
save(function() {
     console.log("save is done running, do something here");
});
Paul Zepernick
  • 1,452
  • 1
  • 11
  • 25
  • This is much worse than the other answer - what happens if `somePromise` doesn't fulfill but rejects? What happens if `callBack` throws? What about potential return values? If you already have a promise you almost never need to do callbacks like this. – Benjamin Gruenbaum Sep 29 '17 at 18:04
  • Good points, I am not sure what the OP is actually trying to accomplish. If it is to wait for all promises to be done, then a $.when() would be better here – Paul Zepernick Sep 29 '17 at 18:07
-1

You may need to make your save function to return a Promise

function save() {
  //does some stuff here
   return new Promise((resolve, reject) => {

  
    somePromise.then(x => {
     resolve("Something1")
    }).then(z => {
      //return statement that makes you leave the function
      resolve("Something2")
    }) 
  
  }
}

save().then(x => {
  console.log(x); // x = something1 || something2
})
Mohamed Abbas
  • 2,228
  • 1
  • 11
  • 19