phambaonam
phambaonam

Reputation: 45

Can callbacks be used with promises or is it one way or the other in node.js?

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

Answers (1)

Lukasz Wiktor
Lukasz Wiktor

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

Related Questions