I've countered the same issue if i understand your question correctly this is the solution you need, and you can also use it in loops, i hope this help you, if this is not your answer just tell me to update my answer
const AsyncFuncion = async () => {
let interval = 2000;
const delayPromise = (data, delayDuration) => {
return new Promise((resolve) => {
setTimeout(() => {
// here you can do your operations on db
resolve();
}, delayDuration)
});
};
try {
const userData = // the data you want from db or you can use http request to get that data
const promises = userData.map((data, index) => delayPromise(data, index * interval));
await Promise.all(promises);
setTimeout(function(){
console.log('done') // after 10 minitues it'll repeate it self you can disable it also
AsyncFuncion()
}, 1000 * 60 * 10)
} catch (e) {
console.error('AsyncFuncion', e);
}
}
AsyncFuncion();
As a follow-up to my comment: `verifyExistingUsers` has no reason to 'return new promise'. Node will wrap your return statement in a promise on its own because the function is 'async'.
The original error here is because you effectively cannot use `await` in the anonymous, non-async function, `((resolve, reject) => {})`.
Instead of returning a new promise, you will just return the variable you want when you are done pushing data into the array. By doing so and declaring the function as 'async', Node will wrap your return value in a promise that you await somewhere else.
async function verifyExistingUsers(db, users) {
var companies = []
for (const [index, user] of users.entries()) {
let company = await getUserCompany(db, user)
companies.push(company)
if (index === users.length-1) {
return companies; //effectively returns a promise that resolves to companies
}
}
}