Update: I added a brief pause after writing to the file, it was only then did the shell commands work.
async function testRun() {
await createInsertCurlReq.createInsertCurlReq(process.argv[2]);
await timeout(3000);
shell.chmod("+x", "./curl.sh");
shell.exec("./curl.sh");
}
}
Original Question
My .then()
block after createInsertCurlReq.createInsertCurlReq(process.argv[2])
does not run. How should I rewrite this so that it does? I noticed if I don't remove the file and just append to, the script runs.
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 };
In createInsertCurlReq you use then chaining jsut to pass an array when there is no asynchronous operations. try this format:
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"`
);
}
}
}