Search code examples
javascriptnode.jsasync-awaites6-promiseasynccallback

should Node.js library support both promises and callbacks


I m working on a Node.js library project that exposes asynchronous APIs to the user. I haven't worked in javascript for long, but it seems that several years ago, callbacks were used to handle asynchronous results/errors. Then promises were introduced in ES6 and async-await in ES8 (which is just more convenient way to use promises).

My question is what would a typical user of the API currently expect? I noticed an idiom in several projects where both promises and callbacks are supported, in the way that a function takes a callback as a last argument and if it is not provided, returns a Promise.

I'm wondering if this idiom should be followed in current projects or should callbacks be removed all together? Would anybody still use callbacks?

I noticed that async-await is becoming the dominant style but Node.js API itself is still callback-based (in fact the APIs usually return an event emitter, not a promise, so that user can register events on the return value).

So I'm just looking for general input from Node.js community about which direction to take.

Thanks.

Edit:

Thank you for the answers. I was asked to clarify couple of things about the project in case there are more recommendations:

(1) The API is intended to be used to access a specific product

(2) All of the calls involve network communication, basically request/response.

We definitely intend to support promises (such that each request gives user a promise that can be fulfilled or rejected), the only question is whether callbacks should still be supported as well.

Perhaps I can rephrase the questions as to be less opinion based:

1) For Node.js libraries released recently (after async-await became supported in the language) and having requirements similar to above, what is the predominant style? Could you please point me to any examples?

2) Could there be any scenario in which application would prefer handling the asynchronous result/error via callback instead of a promise?

Thanks.


Solution

  • How big is your intended user base?

    If it’s small - ie contained within an easily defined group and modern tech stack, play the dictator and choose just one style.

    If it’s large and has to run on many, possibly legacy platforms, consider just offering callbacks, or offer multiple flavours.