Node.js 使用承诺在nodejs中执行一系列命令
我想通过nodejs中的串行线,使用Q命令一步一步地处理一系列命令Node.js 使用承诺在nodejs中执行一系列命令,node.js,q,Node.js,Q,我想通过nodejs中的串行线,使用Q命令一步一步地处理一系列命令 var cmdArr = ['cmd1', 'cmd2','cmd3']; 我不知道如何建立这个。我曾想过这样的事情,但没有成功: Q().then(function() { cmdArr.forEach(command) { //here to initialize the promise?? } }); 重要的是保持顺序,并且能够在每个步骤之间使用Q.delay。假设要执行的命令是某种异步函数调用: v
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
,所以可能会做得更好
为完整起见,以下版本使用:
对阵列上的一系列异步操作进行排序的常见设计模式是使用
.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()
。什么是“命令”?可能是重复的感谢,这正是我想要的。在异步操作中,我另外使用Q.defer()返回已解决或拒绝的promis。@solick-我只是好奇,为什么您不按照您的要求使用基于.reduce()
和使用Q的.delay()
的简单设计模式?
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
});