gpt4 book ai didi

node.js - 在nodejs中使用promise执行一系列命令

转载 作者:太空宇宙 更新时间:2023-11-03 23:35:06 36 4
gpt4 key购买 nike

我想使用 Q Promise 通过 Nodejs 中的串行线逐步处理一系列命令。

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 的版本:

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

关于node.js - 在nodejs中使用promise执行一系列命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33681178/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com