簡體   English   中英

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

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

我想通過使用Q Promise通過Node.js中的串行線逐步處理一系列命令。

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

我不確定如何構建它。 我想到了這樣的事情,但是沒有用:

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

重要的是要保持順序並能夠在每個步驟之間使用Q.delay。

假設要執行的命令是某種異步函數調用:

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!');
});

我對q不太熟悉,所以可以做得更好。

為了完整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!');
});

對數組上的一系列異步操作進行排序的常見設計模式是使用.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
});

注意,我還顯示了您可以在其中插入Q的.delay()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM