0

While trying to move my code to promises after working only with callbacks, (without breaking the function's interface) I've encountered an issue. in a code example like this:

function callMeWithCallback(args, next) {
    Promise.resolve()
     .then(()=> {
       return next("some error will be thrown here");
     }).catch((error)=> {
        return next("Error in callMeWithCallback func");
     });
 }

callMeWithCallback(args, function(){
     throw "some error";
})

What happens is that after resolving the promise in callMeWithCallback func and calling the callback once, an error is thrown, and the code comes back the catch in the callMeWithCallback function and calls again the callback.

I would like the function callMeWithCallback to call the call back only once (wether i case of an error or not) what changes do I need to imply?

yuria
  • 541
  • 2
  • 7
  • 22
  • 1
    [`Promise.resolve`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve) is not a constructor. – Xotic750 Sep 14 '16 at 13:47
  • 1
    Have a look at the [difference between `.then(…).catch(…)` and `.then(…, …)`](http://stackoverflow.com/q/24662289/1048572) – Bergi Sep 14 '16 at 13:53

1 Answers1

1

I warmly recommend that you use a library like bluebird that normalizes this for you - your code would be:

function callMeWithCallback(args, next) {
  // in real code always reject with `Error` objects
  var p = Promise.reject("some error will be thrown here");
  p.asCallback(next); // converts a promise API to a callback one, `throw`s.
  return p;
}

This guarantees "next" will be called once at most.

If you do not want bluebird you can implement this yourself:-

   function asCallback(promise, callback) {
     promise.then(v => callback(null, v), e => callback(e));
   }

Which would be fine as long as you keep the calls in one place. The important part is to not dispatch the calls to "next" yourself.

notionquest
  • 37,595
  • 6
  • 111
  • 105
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • thanks @benjamin. what do you mean in 'The important part is to not dispatch the calls to next yourself.' if the asCallback func calls it in one place? – yuria Sep 14 '16 at 13:54
  • 1
    Yes, exactly. Sorry, was in a rush (still kind of am) and didn't want to leave you hanging without an answer. – Benjamin Gruenbaum Sep 14 '16 at 14:01