sridhar
sridhar

Reputation: 881

how to resolve values in nodejs promises

I am new to promises Q node module.

How to resolve values for promise object.

Here is my example:

function fs_readFile (file, encoding) {
 var deferred = Q.defer()
 fs.readFile(file, encoding, function (err, data) {
  if (err) 
    deferred.reject(err)
  else 
    deferred.resolve(data)
 })
 return deferred.promise
}

Now i am calling the function:

var promise=fs_readFile('myfile.txt').then(console.log, console.error);

Now i can get my file content data from then fulfill call back function but how can i get my file content data from returned promises object. like synchronously .

can any one help me!!

Upvotes: 0

Views: 3234

Answers (2)

Vietnhi Phuvan
Vietnhi Phuvan

Reputation: 2804

function fs_readFile (file, encoding) {
var deferred = Q.defer()
fs.readFile(file, encoding, function (err, data) {
  if (err) 
    deferred.reject(err)
  else 
    deferred.resolve(data)
  })
  return deferred.promise.then(console.log, console.error)
}

var promise=fs_readFile('myfile.txt','utf-8')

Upvotes: 0

ForbesLindesay
ForbesLindesay

Reputation: 10712

Promises help by encapsulating the result of an asynchronous operation but because the operation hasn't finished yet you can't actually get the result synchronously. You can get some of the appearance of synchronous behaviour though. You get the concept of functions taking arguments and returning a value. You also get error handling that climbs the stack in the same way that errors would in synchronous code.

In ES6 (the next version of JavaScript, partially supported by some of the newest browsers) you also get generators which helps you write even more synchronous seeming code.

Consider your readFile operation, if it were synchronous you could write something like:

function readJsonSync(filename) {
  return JSON.parse(fs.readFileSync(filename, 'utf8'));
}

with the promise returning version in the current version of JavaScript you could write

function readJson(filename) {
  return fs_readFile(filename, 'utf8').then(JSON.parse);
}

If you wanted to do the same with callbacks rathe than promises you'd have to write the following to get proper error handling behaviour:

function readJsonCallback(filename, callback){
  fs.readFile(filename, 'utf8', function (err, res){
    if (err) return callback(err)
    try {
      res = JSON.parse(res)
    } catch (ex) {
      return callback(ex)
    }
    callback(null, res)
  })
}

With ES6 you can write:

var readJson = Q.async(function* (filename){
  return JSON.parse(yield fs_readFile(filename, 'utf8'))
})

The yield "awaits" the promise and gives you the resolution value. The caveat is that the function that contains yield must be wrapped in Q.async and will return a promise itself.

If you want a more in depth look at this, or simply prefer videos to text, I gave a talk on this topic that you can find on YouTube: http://youtu.be/qbKWsbJ76-s

Upvotes: 1

Related Questions