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?
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?
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
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"))
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.