I am writing code to fetch the data from the api and save it in the mongodb database. The code I have written is:
getSquadList: async (ctx) => {
var query = ctx.request.query;
var squadList = await getSquadsOfMatch(query.matchId);
if (squadList.length <= 1) {
var response = await axios.get(
`${strapi.config.currentEnvironment.getSquadListApi}?apikey=${strapi.config.currentEnvironment.cricApiKey}&unique_id=${query.matchId}`
);
squadList = response.data.squad;
var match = await Match.findOne({
unique_id: query.matchId
});
var team1Squad, team2Squad;
await squadList.forEach(async squad => {
if (squad.name === match['team-1']) {
team1Squad = {
name: match['team-1'],
match_id: match['unique_id'],
match: match['_id'],
};
await new Squad(team1Squad).save();
console.log('1');
} else if (squad.name === match['team-2']) {
team2Squad = {
name: match['team-2'],
match_id: match['unique_id'],
match: match['_id'],
};
await new Squad(team2Squad).save();
console.log('2');
}
});
squadList = await getSquadsOfMatch(query.matchId);
console.log('3');
}
ctx.send(squadList);
}
I have used console.log() to see the execution order. The order I want is 1 2 3 but the actual output is 3 1 2 How can I make the program to execute these lines in the last. squadList = await getSquadsOfMatch(query.matchId); console.log('3');