Working with Promises

Simple things to remember when working with Promises

Posted by Jack Furr on February 28, 2018

Promise Contructor

Over the past few months I've started embracing Promises and async/await in my daily coding sessions.

I find that the only time I need to use a Promise contructor is when I need to call a function that uses callbacks. If you are calling a function the returns a Promise, there's no need to use a Promise contructor.

See the Pen yvZvbx by Jack Furr (@jackfurr) on CodePen.

Converting Callback Functions

In some cases it's just not possible to make complete changes to your codebase to use Promises everywhere. To help with the migration from callbacks to Promises, I've found that wrapping the function in a Promise constructor and returning a callback (if supplied) or the Promise if the callback is not supplied, works well.

Callback style

See the Pen gvqvaL by Jack Furr (@jackfurr) on CodePen.

Hybrid style (Promise/Callback)

See the Pen KQJQzo by Jack Furr (@jackfurr) on CodePen.

Now I can call the code and pass in a callback and it will still work as before. But for the new code that I am writing where I am using Promises, I can call the same function but not pass in a callback and the function will return a Promise.

At some point you should remove the Hybrid-style code and just use Promises.

Thanks for checking out this short code review, and good luck!