user6242359
user6242359

Reputation:

promisifyAll in bluebird.js

I am trying to understand how promisifyAll works. i am trying hard to understand the example given in their documentation. Can anyone please give me a simple example, how it works? I am trying to understand the concept and how we can use it. Thank you

var objects = {}; 

objects.first = function(){
  console.log("First one is executed");
}

objects.second = function(){
    console.log("second one is executed");

}

objects.third = function(){
    console.log("third one is executed");
}

how can we promisify the objects variable? or something like that.

Upvotes: 0

Views: 448

Answers (1)

Gio Polvara
Gio Polvara

Reputation: 26988

First, you need to understand how a nodeFunction works. It takes a callback function as the last argument. This callback takes two arguments, the first one is error and the second the data. Consider for example require("fs").readFile:

// This is the callback
function callback (error, data) {
  if (error) {
    console.error('There was an error', error)
  } else {
    console.log('This is the data', data)
  }
}
require('fs').readFile('my-file.txt', callback)

Note that this is a convention, there's nothing in JS itself that enforces it.

Let's move to Promise.promisify now. This method takes a nodeFunction and returns a promisified version of it. This is more or less what it does:

function promisifiedReadFile (filePath) {
  return new Promise(function (fulfill, reject) {
    require('fs').readFile(path, function (error, data) {
      if (error) { reject(error) } else { fulfill(data) }
    })
  })
}

It's a bit verbose but as you can see you now have a version of readFile that returns a promise instead of accepting a callback. Of course, this example is hard-coded for readFile, Promise.promisify works for any nodeFunction instead:

const promisifiedReadFile = Promise.promisify(require('fs').readFile)

The two promisifiedReadFile methods work in the same way.

Last, Promise.promisifyAll takes an object, goes through it and finds all the methods, it then applies Promise.promisify to each of them.

So, if you call Promise.promisifyAll(require('fs')) you get back a version of the fs module where all the methods return promises instead of accepting callbacks.


About your example I'm not sure what you're trying to achieve but the methods you defined are not nodeFunctions so they can't be promisified.

Upvotes: 2

Related Questions