1

I'm using a third party library that exposes functions of the form function(arg1, arg2, successFunction, errorFunction).

To prevent my code from nesting success functions levels deep, I would like to use Promise.all

Is this possible? If so, how?

Johnny H.
  • 43
  • 3
  • 1
    Possible duplicate of [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – John Nov 06 '17 at 14:29

3 Answers3

1

You can create a Promise wrapper to your third library:

function Promise_wrapper(arg1, arg2){
    return new Promise(function (resolve, reject){
        yourLib(arg1, arg2, function(result){
            resolve(result)
        }, function(error){
            reject(error)
        })
  });
}

obiouvsly now you can call Promise.all() with an array of Promise_wrapper

alfredopacino
  • 2,979
  • 9
  • 42
  • 68
0

You can use promise like below:

function yourMethodReturningPromise(arg1, arg2) {
  return new Promise((resolve, reject) => {
    yourFunctionUsingCallback(arg1, arg2, (something) => resolve(something), () => reject("errors")).  
  });
}

The you can use yourMethodReturningPromise like below:

yourMethodReturningPromise(arg1, arg2).then((res) => {
    console.log("success: ", res);
}, (err) => console.log("errors"))
Faly
  • 13,291
  • 2
  • 19
  • 37
0

It's quite simple: Use the Promise constructor and just pass resolve as the successFunction callback and reject as the errorFunction callback:

var promise = new Promise((resolve, reject) => {
    libraryFunction(arg1, arg2, resolve, reject);
});

You might want to wrap this in a helper function that takes only arg1 and arg2 as parameters and returns the promise.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375