Reputation: 45
I'm new to NodeJs. I read this article and found a question:
Can callbacks be used with promises or is it one way or the other?
I searched the answer but it is not clear. So what is the answer?
Thanks.
Upvotes: 1
Views: 111
Reputation: 20422
You can always turn a callback into a promise to make it cooperate with your other promises smoothly. Let's assume asyncFunc
is a function that takes a callback. You can turn it into a promise this way:
new Promise((resolve, reject) => {
asyncFunc((error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
}
});
Most libraries implementing promises offer a shortcut for the above code construct:
Promise.promisify(asyncFunc);
Upvotes: 1