I am trying to use an async call however whenever I put the await command word in, the script fails to run. Any suggestions gratefully accepted.
alternative code at bottom based on comment provided
async function masterDeploy(PrimaryControl){
//2. Collect learning event dates from programme
LearnEvents = progLearnerEvent(progGuid)
.then(LearnEvents =>{
console.log(LearnEvents)
for (var b = 0; b < LearnEvents.length; b++) {
retLearnEvents(LearnEvents[b],progGuid,b) //need to wait for these results before moving to next loop, code does not run if await placed at beginning of this line
console.log(FlightPlanArray)
learnEventsArrComb.push(FlightPlanArray)
console.log(learnEventsArrComb)
}
return learnEventsArrComb
})
.then(learnEventsArrComb => {
console.log(learnEventsArrComb)
})
.catch(error =>
{DisplayError(error)}
);
alternative starts here
LearnEvents = progLearnerEvent(progGuid)
await (LearnEvents =>{
//.then(LearnEvents =>{
console.log(LearnEvents)
for (var b = 0; b < LearnEvents.length; b++) {
await retLearnEvents(LearnEvents[b],progGuid,b) //need to wait for these results before moving to next loop, code does not run if placed at beginning of this line
console.log(FlightPlanArray)
learnEventsArrComb.push(FlightPlanArray)
console.log(learnEventsArrComb)
}
return learnEventsArrComb
})
//.then(learnEventsArrComb => {
// console.log(learnEventsArrComb)
//})
//.catch(error =>
// {DisplayError(error)}
//);
}
you can do it like this:
const masterDeploy = async (PrimaryControl) =>{
//2. Collect learning event dates from programme
LearnEvents = await progLearnerEvent(progGuid)
.then(LearnEvents =>{
console.log(LearnEvents)
for (var b = 0; b < LearnEvents.length; b++) {
await retLearnEvents(LearnEvents[b],progGuid,b) //need to wait for these results before moving to next loop, code does not run if await placed at beginning of this line
console.log(FlightPlanArray)
learnEventsArrComb.push(FlightPlanArray)
console.log(learnEventsArrComb)
}
return learnEventsArrComb
})
.then(learnEventsArrComb => {
console.log(learnEventsArrComb)
})
.catch(error =>
{DisplayError(error)}
);
try this instead...
You need to add await when you call to masterDeploy func
function main(){
await masterDeploy(info)
}
also, I recommend to do these changes in your code:
async function masterDeploy(PrimaryControl){
//2. Collect learning event dates from programme
try{
const LearnEvents = await progLearnerEvent(progGuid)
console.log(LearnEvents)
for (let b = 0; b < LearnEvents.length; b++) { retLearnEvents(LearnEvents[b],progGuid,b) //need to wait for these results before moving to next loop, code does not run if await placed at beginning of this line
console.log(FlightPlanArray)
learnEventsArrComb.push(FlightPlanArray)
console.log(learnEventsArrComb)
}
}
catch(error){
DisplayError(error)
}
}