更新:我在写入文件后添加了一个短暂的暂停,然后 shell 命令才起作用。
async function testRun() {
await createInsertCurlReq.createInsertCurlReq(process.argv[2]);
await timeout(3000);
shell.chmod("+x", "./curl.sh");
shell.exec("./curl.sh");
}
}
<小时/>
原始问题
createInsertCurlReq.createInsertCurlReq(process.argv[2])
之后的 .then()
block 未运行。我应该如何重写它才能做到这一点?我注意到如果我不删除该文件而只是附加到该文件,脚本就会运行。
async function testRun() {
if (fs.existsSync('./curl.sh')) {
shell.rm('-rf', './curl.sh');
}
createInsertCurlReq.createInsertCurlReq(process.argv[2]).then(() => {
shell.chmod('+x', './curl.sh');
shell.exec('./curl.sh')
return
})
}
}
curlCreation.js
function createInsertCurlReq(filePath) {
return utils
.readJSONFileOnDisk(filePath)
.then(data => {
obj = JSON.parse(data);
let resultArr = [];
for (let key in obj) {
for (let innerKey in obj[key]) {
let arrayNew = {};
arrayNew[key] = obj[key][innerKey].resolved;
resultArr.push(arrayNew);
}
}
return resultArr;
})
.then(data => {
if (!fs.existsSync("./curl.sh")) {
shell.touch("./curl.sh");
}
return data;
})
.then(data => {
for (let i = 0; i < data.length; i++) {
for (let key in data[i]) {
fs.appendFile(
"curl.sh",
`curl -X POST -H "xxx",
function(err) {
if (err) throw err;
}
);
}
}
});
}
module.exports = { createInsertCurlReq: createInsertCurlReq };
最佳答案
在 createInsertCurlReq 中,当没有异步操作时,您可以使用链接 jsut 来传递数组。尝试这种格式:
async function testRun() {
if (fs.existsSync('./curl.sh')) {
shell.rm('-rf', './curl.sh');
}
await createInsertCurlReq.createInsertCurlReq(process.argv[2])
shell.chmod('+x', './curl.sh');
shell.exec('./curl.sh');
}
async function createInsertCurlReq(filePath) {
const data = await utils.readJSONFileOnDisk(filePath);
const obj = JSON.parse(data);
let resultArr = [];
for (let key in obj) {
for (let innerKey in obj[key]) {
let arrayNew = {};
arrayNew[key] = obj[key][innerKey].resolved;
resultArr.push(arrayNew);
}
}
if (!fs.existsSync("./curl.sh")) {
shell.touch("./curl.sh");
}
for (let i = 0; i < resultArr.length; i++) {
for (let key in resultArr[i]) {
fs.appendFileSync(
"curl.sh",
`curl -X POST -H "xxx"`
);
}
}
}
关于javascript - 异步问题,无法在 .then 之后运行 shelljs 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52938349/