DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
derekenos profile image
Derek Enos • Edited

One of my recent favorites is this helper to convert a callback-based JS function to an awaitable:

function makeAwaitable (func, callbackArgIndex) {
  /* Return an awaitable version of a callback-based function.                                     

     Example:                                                                                      

       // Create an awaitable version of setTimeout, specifying the index                          
       // of the expected callback argument index (i.e. 0).                                        
       const awaitableSetTimeout = makeAwaitable(setTimeout, 0)                                    

       // Invoke the awaitable setTimeout, omitting the callback arg.                              
       await awaitableSetTimeout(1000)                                                             
       // Returns 1 second later.                                                                  

   */
  return (...args) => new Promise(
    (resolve, reject) => {
      // Splice resolve() into args at the callbackArgIndex location.                              
      args.splice(callbackArgIndex, 0, resolve)
      // Invoke func, reject the promise on error.                                                 
      try {
        return func(...args)
      } catch (e) {
        reject(e)
      }
    }
  )
}
Enter fullscreen mode Exit fullscreen mode