ES5,等待Promise.each完成

时间:2016-04-26 05:31:44

标签: node.js loops promise bluebird

var Promise = require('bluebird');

var device_execute_command = function(command_arr) {
  return new Promise(function (resolve, reject) {

    Promise.each(command_arr, function(command) {
      return device_run_single_command(command).then(function(command) {
        console.log();
        console.log("finish one command");

        return is_device_has_latest_state(command);
      }).then(function(command_with_condi) {
        console.log();
        console.log("has latest state?");

        if(command_with_condi.is_device_has_latest_state == 'false') {
          console.log();
          console.log("no state on server");

          device_set_entire_state_in_server(config.device_unique_name, command_with_condi.command_id);
        }
        else {
          // The server has device's state, so device notifies server to advance state on server
          console.log();
          console.log("has state on server");

          device_set_next_state(command_with_condi.command_id);

        }

      });
    }) // End each loop
    .then(function() {
      // Now the loop is finished, we need to resolve.
      var obj = {
        all_pending_commands_executed: true
      };

      resolve(obj);
    });

  });
}

说command_arr.length === 1;

当前输出:

完成一个命令

有最新状态吗?

all_pending_commands_executed:true

服务器上没有状态

预期输出:

完成一个命令

有最新状态吗?

服务器上没有状态

all_pending_commands_executed:true

0 个答案:

没有答案