我正在制作一个基于web的工具,它连接到一个名为回放-设置的现有的基于shell的框架中。
它们有一个名为/retropie- use /retropie_Packages.sh的shell脚本,您可以使用它来安装、获取依赖关系,甚至编译不同的程序。
一个问题是packages.sh不应该在给定时刻多次运行,所以我需要设置一个每次运行一个队列。
我认为我可以使用承诺队列来防止多次执行,但是每当我运行execFile时,它就会立即运行命令,而不是当它到达队列中的某个位置时。
下面是我的示例代码:
downloadTest.sh (下载具有唯一名称的10文件):
filename=test$(date +%H%M%S).db
wget -O ${filename} speedtest.ftp.otenet.gr/files/test10Mb.db
rm ${filename}节点码
const Queue = require('promise-queue')
const { spawn,execFile } = require('child_process');
var maxConcurrent = 1;
var maxQueue = Infinity;
var que = new Queue(maxConcurrent, maxQueue);
var testFunct = function(file)
{
var promise = new Promise((reject,resolve) => {
execFile(file,function(error, stdout, stderr) {
console.log('Finished executing');
if(error)
{
reject();
} else
{
resolve(stdout);
}
});
})
return promise;
}
var test1 = testFunct('/home/pi/downloadTest.sh')
var test2 = testFunct('/home/pi/downloadTest.sh')
var test3 = testFunct('/home/pi/downloadTest.sh')
que.add(test1);
que.add(test2);
que.add(test3);发布于 2017-10-07 04:05:04
你的代码非常接近工作。主要的问题是,您正在执行testFunct(),这反过来会返回一个承诺,即立即开始执行其中的内容。要解决这个问题,可以使用Function.prototype.bind()将参数绑定到函数而不执行它。如下所示:
que.add(testFunct.bind(null, '/home/pi/downloadTest.sh'));
que.add(testFunct.bind(null, '/home/pi/downloadTest.sh'));
que.add(testFunct.bind(null, '/home/pi/downloadTest.sh'));或者,您可以使用async/await,这使得队列的实现变得简单,这反过来又允许您放弃对promise-queue的依赖。
const execFile = require("util").promisify(require("child_process").execFile)
(async function () {
let scripts = [
"/home/pi/downloadTest.sh",
"/home/pi/downloadTest.sh",
"/home/pi/downloadTest.sh"
]
for (let script of scripts) {
try {
let { stdout, stderr } = await execFile(script)
console.log("successfully executed script:", script)
} catch (e) {
// An error occured attempting to execute the script
}
}
})()上面代码中有趣的部分是await execFile(script)。当您await一个表达式时,整个函数的执行会暂停,直到execFile函数返回的承诺解析或拒绝为止,这意味着您有一个按顺序执行的队列。
https://stackoverflow.com/questions/46616218
复制相似问题