The role of promisify

Instead of passing in callback arguments to implement callback execution (or synchronous execution), invoke the promise. Then method to implement logical synchronization.

Code implementation

function promisify(func) {
  return function (. args) {
    return new Promise( (resolve, reject) = > {
      let callback = function(. args) {
        resolve(args)
      }
      // Insert a callback into the func function, so that when the callback is called in the func, it is actually executed
      // We define the callback function here, and then call resolve in our callback,
      // In this way, the operation that was intended to be performed through the callback can be performed in the then function
      func.apply(null, [...args, callback])
    })
  }
}

Copy the code

Using the instance

// Foo can be any function that calls the callback function
function foo (str1, str2, callback) {
  setTimeout( (a)= > {
    console.log('setTimeout')
    // The callback function is identified by the position of the last argument, regardless of the name
    callback(str1, str2)
  }, 1000)}// Agent is no longer a function foo, but a custom anonymous function we return in promisify
// So you don't have to worry about passing a callback.
let agent = promisify(foo)

agent('hello'.'world')
  .then( res= > {
    console.log(res)
  })
Copy the code

The output

setTimeout
[ 'hello'.'world' ]
Copy the code

conclusion

Promisify is useful in actual development and hopefully useful.