简体   繁体   English

使用Promise在Node.js中执行一系列命令

[英]Using promises to execute a series of commands in nodejs

I want to process a series of commands step by step via serial line in nodejs by using Q promises. 我想通过使用Q Promise通过Node.js中的串行线逐步处理一系列命令。

var cmdArr = ['cmd1', 'cmd2','cmd3'];

I am not sure how to build this. 我不确定如何构建它。 I thought about something like this but it did not work: 我想到了这样的事情,但是没有用:

Q().then(function() {
  cmdArr.forEach(command) {
     //here to initialize the promise??
  }
});

Important is to keep the sequence and are able to use Q.delay in between each step. 重要的是要保持顺序并能够在每个步骤之间使用Q.delay。

Assuming that the commands you want to perform are some sort of async function call: 假设要执行的命令是某种异步函数调用:

var Q = require('q');

// This is the function you want to perform. For example purposes, all this
// does is use `setTimeout` to fake an async operation that takes some time.
function asyncOperation(input, cb) {
  setTimeout(function() {
    cb();
  }, 250);
};

function performCommand(command) {
  console.log('performing command', command);
  // Here the async function is called with an argument (`command`),
  // and once it's done, an extra delay is added (this could be optional
  // depending on the command that is executed).
  return Q.nfcall(asyncOperation, command).delay(1000);
}

// Set up a sequential promise chain, where a command is executed
// only when the previous has finished.
var chain = Q();
[ 'cmd1', 'cmd2', 'cmd3' ].forEach(function(step) {
  chain = chain.then(performCommand.bind(null, step));
});

// At this point, all commands have been executed.
chain.then(function() {
  console.log('all done!');
});

I'm not overly familiar with q so it may be done better. 我对q不太熟悉,所以可以做得更好。

For completeness, here's a version using bluebird : 为了完整bluebird ,这是使用bluebird的版本:

var Promise = require('bluebird');

...

var asyncOperationAsPromised = Promise.promisify(asyncOperation);

function performCommand(command) {
  console.log('performing command', command);
  return asyncOperationAsPromised(command).delay(1000);
}

Promise.each(
  [ 'cmd1', 'cmd2', 'cmd3' ],
  performCommand.bind(null)
).then(function() {
  console.log('all done!');
});

A common design pattern for sequencing a bunch of async operations on an array is to use .reduce() like this: 对数组上的一系列异步操作进行排序的常见设计模式是使用.reduce()如下所示:

var cmdArr = ['cmd1', 'cmd2','cmd3'];

cmdArr.reduce(function(p, item) {
    return p.delay(1000).then(function() {
        // code to process item here
        // if this code is asynchronous, it should return a promise here
        return someAyncOperation(item);
    });
}, Q()).then(function(finalResult) {
    // all items done here
});

Note, I've also shown where you can insert Q's .delay() as requested. 注意,我还显示了您可以在其中插入Q的.delay()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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