Search code examples
javascriptpromisees6-promiseclient-side-scripting

Callbacks or promises for new client-side javascript library?


As of 2017, all current versions of web browsers have support for ES6 promises.

If I were now to create a browser-side javascript library, what are the pros and cons (or related considerations) of using callback-style functions versus using promises? Is it still an option to consider using callbacks?

Note: the operations of the library are I/O related, therefore asynchronous operations fit well, so I don't think synchronous operations are an option.


Solution

  • Well, of course you should use promises. It's just a much better conceptual framework for handling async things. If you don't, the first thing 90% of your users will do is to wrap your APIs into promises anyway, and you don't want to make them do that, do you?

    In theory you could adopt the dual-mode approach of having the presence or absence of a callback parameter control whether a particular API behaves in callback or promise-like fashion. Many libraries with roots in pre-promise days take this route. It's doubtful you would want to take this approach for a new library.

    You can ship your library with the ability to integrate with a promise library of the user's choice, in case he doesn't like, or can't use, native promises. The user would initialize your library with something like initNcasasLibrary(Promise). Or you could just have your user ensure that Promise is available by making sure to include a polyfill if he's targeting browsers that might not have it.