简体   繁体   中英

error while using the Q library nodeJS

I have the following nodeJS code.I need to get the machines for each service from the redis database. I am using the 'q' library to simplify the callback problem. However I do not get the output.

I am new to node/callbacks/q. Where is my mistake in the code?

I have a controller.js file with the following code

function getMachines(services) {
  var machines = Q.fcall(function() {});
  services.forEach(function(service) {
    var value = function() {
      var deferred = Q.defer();
      redisDB.readfromRedis(service, function(result) {
        deferred.resolve(result);
      });
      return deferred.promise;
    }
  });
  return machines;
}

testController.js(calling the getMachines function from the controller.js )

var services = ['dashDb22', 'service1', 'service2', 'service3']
var output = controller.getMachines(services)
console.log(output);

RedisDb.js

function readfromRedis(key, callback) {
  client.smembers(key, function(error, value) {
    if (error) {
      throw error;
    }
    console.log('VALUE IS: = ' + value);
    callback(value);
  });
}

Your getMachines() doesn't do much, machines is useless and inside your forEach() , you're storing a function you never execute. Your code being simple, you don't really need to use Q, nodejs has a native Promise support.

function getMachines(services) {
    // create an array of promises
    var myPromises = services.map(function (service) {
        // for each service, create a Promise
        return new Promise(function (resolve, reject) {
            redisDB.readfromRedis(service, function (result) {
                resolve(result);
            });
        });
    })
    // takes an array of promises and returns a promise for when they've all 
    // fulfilled (completed successfully) with the values as the result
    return Promise.all(myPromises);
}

getMachines(services).then(function (machines) {
    // use machines here
});

You could also make readfromRedis() a promise to make it simpler to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM