In order to convert any callback API to promises assuming the promisify
and promisifyAll
version doesn't fit - you can use the promise constructor.
Creating promises generally means specifying when they settle - that means when they move to the fulfilled (completed) or rejected (errored) phase to indicate the data is available (and can be accessed with .then
).
new Promise((fulfill, reject) => { // call fulfill/reject to mark the promise someCallbackFunction((data) => { fulfill(data); // we mark it as completed with the value }) });
As an example, let's convert setTimeout
to use promises:
function delay(ms) { // our delay function that resolves after ms milliseconds return new Promise((resolve, reject) => { // return a new promise setTimeout(resolve, ms); // resolve it after `ms` milliseconds have passed }) } // or more concisely: const delay = ms => new Promise(r => setTimeout(r, ms));
We can now use it like a regular promise returning function:
delay(1000).then(() => console.log("One second passed")). then(() => delay(1000)). then(() => console.log("Another second passed"));