Implement promisify()

June 17, 2021

JavaScript
bigfrontend.dev

Promises are used in many codebases and drives the bulding blocks for synchronous methods. It allows your state to take direction in a route in which you give it. MDN represents it best in a machine state analogy:

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.

A Promise is a special JavaScript object that links these states together.


My Definition of a Promise

Bring back my coffee, and please make sure it's not an iced coffee šŸ˜…. Isn't that Promise. On a serious note, it's a promise to return something eventually. MDN has many examples on how you can chain things together and don't have to be explicit.


How to promisfy a function?

One of the most dreaded interview questions most developers don't want to see (because it can catch you off-guard). Luckily, I had to chance to try it out on bigfrontend.dev. The idea is you'll have a function that's gonna eventually return a function, and then when you invoke that, it's gonna be a Promise, so you can chain it.

Here's my implementation:

1/**
2 * @param {(...args) => void} func
3 * @returns {(...args) => Promise<any}
4 */
5 function promisify(func) {
6 // your code here
7 return function(...args) {
8 return new Promise((resolve, reject) => {
9 const cb = (error, data) => {
10 if (error) {
11 reject(error)
12 } else {
13 resolve(data)
14 }
15 }
16 func.apply(this, args.concat(cb));
17 })
18 }
19}
20
21const func = (arg1, arg2, cb) => {}
22
23let promiseFn = promisify(func);
24
25// chaining process
26promiseFn().then(...).then(...)

Conclusion

A promise gives us more flexibility and better code flow. It allows us to direct a natural state of instructions that's similar to how I like to place my door dash order. Kinda.

Resources:


my shoe
Iā€™m Marlon but you can call me Mars. Software Engineer. Music lover. Bay Area Native. Feel free to Contact me.
  • debouncing-react ā†’
  • ā† lets-deep-dive-into-hooks