CodewCaro.
When writing a function in Javascript/Typescript have you gotten Unexpected reserved word 'await'?
The error "Unexpected reserved word 'await'. In your JavaScript code this is because the misuse of the await keyword inside a callback function. In JavaScript, await, can only be used inside an async function. However, forEach does not accept an async callback. This means that you can't use await directly inside the callback function provided to forEach
For example, await api.getData(record) is inside the forEach callback, which is not marked as async.
This can be fixed in some ways.
Using for...of loop: This allows usage of await inside the loop.
async function functionStarted() {
for (const record of selectedRecords) {
const modelOfRecord = await api.getData(record);
console.log(modelOfRecord, 'modelOfRecord');
}
onRunTranslationAction({
record: selectedRecord,
model: selectedModel,
fields: selectedFields
});
//'modelOfRecord' will only hold the last value from the loop
return modelOfRecord;
}
Using Promise.all with map: If you need to process all records in parallel and wait for all of them to complete.
async function functionStarted() {
const modelsOfRecords = await Promise.all(selectedRecords.map(record => api.getModels(record)));
modelsOfRecords.forEach(modelOfRecord => {
console.log(modelOfRecord, 'modelOfRecord');
});
onRunTranslationAction({
record: selectedRecord,
model: selectedModel,
fields: selectedFields
});
// This will return an array of all modelOfRecords
return modelsOfRecords;
}
In the second approach, Promise.all waits for all promises returned by api.getModels(record) to be resolved, and map is used to create an array of these promises. This is useful if api.getData can be called in parallel for different records.