I am wanting the for loop to run sequentially, finishing one loop completely before moving to the next. The loop is putting a JSON message into another JSON message then sending it to a function that begins posting to an api. I need that function to complete before moving on to the next item in the JSON. p is the item name that is being used to post back whether it was successfully posted to the db via the api service.
Here is the bit of code simplified for this question.
let processJson = function(items) {
for (const p in items) {
let newObj = {
"key1": items[p].key1,
"key2": items[p].key2,
"keySpecial": items[p].key3 + items[p].key4
};
await validateJson(p, newObj);
}
};
I need the validateJson to finish its chain of asynchronous work before moving on to the next p in the loop.
How can I do this?
Here is the validateJson function as requested.
const validateJson = function (id, jsonObj) {
const processItemSchema = {
"properties": {
"key1": {
"type": "string"
},
"key2": {
"type": "string",
"minLength": 3,
"maxLength": 3
},
"keySpecial": {
"type": "string",
"minLength": 4,
"maxLength": 4
}
}
};
const ajv = new Ajv();
let validate = ajv.compile(processItemSchema);
let valid = validate(jsonObj);
if (!valid){
resCallback(id + ": invalid JSON");
}
else{
// Generate Special Flag(s) value, Comma Separated Value
let specialFlag = "";
specialFlag += specialCheck1(jsonObj.keySpecial);
if(specialFlag.length > 0) {
let temp = specialCheck2(jsonObj.keySpecial);
if (temp.length > 0) {
specialCheck += "," + temp;
maintenanceCall(id, jsonObj, specialFlag);
}
else {
mainenanceCall(id, jsonObj, specialFlag);
}
}
else {
specialFlag += specialCheck1(jsonObj.keySpecial);
maintenanceCall(id, jsonObj, specialFlag);
}
}
};
More Code as requested
const maintenanceCall= function (id, jsonObj, specialFlag) {
request.post({
url: 'https://url.poster/something',
auth: {
'user': 'user',
'pass': 'pass',
'sendImmediately': true
},
json: true,
body: {
"Input": {
"InputParameters": {
"KEY": jsonObj.key1,
"Hole": jsonObj.Key2,
"SomeWhere": jsonObj.keySpecial
}
}
}
}
, function (error, response, body) {
if (body.OutputParameters.X_MSG_DATA !== null) {
resCallback(id + , Message: "
+ body.OutputParameters.DATA);
}
else {
const sampCheck = function(smsFlag){
if(flag=== "Y")
return ".X";
else if(flag=== "N")
return "";
else
resCallback(id + ": this item can not be processed");
processItem(id, jsonObj, stats);
}
}
});
};