Tuesday 23 May 2017

How to make the promise return results?

I have a requirement where we need to write a node module using promises. So there would be 3 different promises. Result should be sent back only when all three of them resolve. I have written some code. Currently the result comes as undefined. Let me know what can I add to fix this.

This is the node module code -

var exports = module.exports = {};

exports.getData = function() {
    var Q = require('q');

    var result = 0;

    // Promise 1
    var deferred = Q.defer();

    var promise1 = Q.fcall(function() {
      setTimeout( function(){console.log('hi');deferred.resolve(9);}, 1000 );
      return deferred.promise;
    });


    promise1.then(function(contents) {
        result = result + contents;
      console.log(contents);
    });

    // promise 2

    var deferred2 = Q.defer();

    var promise2 = Q.fcall(function() {
      setTimeout( function(){console.log('hi');deferred2.resolve(10);}, 1000 );
      return deferred2.promise;
    });


    promise2.then(function(contents) {
        result = result + contents;
      console.log(contents);
    });

    // promise3

    var deferred3 = Q.defer();

    var promise3 = Q.fcall(function() {
      setTimeout( function(){console.log('hi');deferred3.resolve(11);}, 1000 );
      return deferred3.promise;
    });


    promise3.then(function(contents) {
        result = result + contents;
      console.log(contents);
    });

};

This is the invoking code -

var x = require('./example5.js');

var result = x.getData();

console.log(' Result is ' + result);

So I need to figure out a way to hold on to the execution of the node module until all the promises are resolved.

Currently the output is -

Result is undefined

P.S I am a newbie to node.js. So if this is something very obvious, please excuse me!



via user3276247

No comments:

Post a Comment