To answer that, you need to consider what you are writing.
Whenever you need to await a function, the enclosing function body must be declared as async:
function outer1() {
await someFunction(); // will error, because outer1 must be async
}
async function outer2() {
await someFunction(); // will work, because outer2 is async
}
In your code, you have something which looks a bit like this:
//Meteor.methods({
function removeData(params) {
params.forEach(
async function(id) {
await someFunction(); // This is await, so ^^this^^ must be async
myFun(.....);
}
);
// Do something
return '......';
//})
Notes:
You do not need an async removeDataunless you use await where you have “Do something”.
If myFun is async, then you must await it.
That example is not really as simple as I have indicated. I don’t know the rest of your code, and you may need additional steps.
Unless you must use async/await (and it’s often unnecessary in Meteor), you must make sure you understand it, as @diaconutheodor says .
I can’t see why that won’t work, unless you’re doing something in code you’ve not shown.
Equally, I can’t see why you can’t get these. However, I also don’t see why you’re setting properties of an intermediate object, which is never used beyond that point.
Is there more code you’re not showing, which may explain the behaviour?
Process array in sequence
To wait the result we should return back to old-school “for loop”, but this time we can use modern version with for…of construction (thanks to Iteration Protocol) for better readability:
Process array in parallel
We can slightly change the code to run async operations in parallel:
async functions return promises immediately when invoked, so the forEach completes and moves on to the console.log line.
The async work delegated to the async functions has not yet completed at this point and so the data is not yet modified.
Since it seems you are already in an async function (since you’ve used await higher in the code), you can wait for all the promises to resolve with await and Promise.all
Promise.all expects an array of promises, so instead of forEach we can use map to create an array of promises
await Promise.all( data.map(aysnc item => { ...
Like forEach, map will iterate over all of the items and run the given function. Unlike forEach, map will return an array with the results of these functions, and given they are async functions, each one will return a promise.
Now we use Promise.all to create a single promise that will resolve when every one of the async functions have finished. And we use await to tell the function to pause until that new promise resolves.
Pausing the function with await means the console.log won’t run until every one of those async functions have finished, meaning it will have the correct data when it does run.