Inside a Node controller method I have this code block that I would like to await
for before continuing with the code that comes next. How can I do this?
I thought this should be done with a Promise (the only one in that controller method) and have tried the code below. But this generates the error below. What am I doing wrong?
TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
const other = new Promise(async function () {
updatedFields.last_login_at = newDateNow();
if (updatedFields.isActivated) {
updatedFields.activated_at = newDateNow();
updatedFields.deactivated_at = null;
} else if (updatedFields.isActivated === false) {
updatedFields.deactivated_at = newDateNow();
updatedFields.activated_at = null;
}
});
await Promise.all(other);
... only when the Promise is completed, continue with the rest of the code
CodePudding user response:
When a promise is created, its state is pending, and when you await it, it waits until it is rejected or resolved. Since you don't resolve or reject, it does not work.
const other = new Promise(async function (resolve,reject) {
updatedFields.last_login_at = newDateNow();
if (updatedFields.isActivated) {
updatedFields.activated_at = newDateNow();
updatedFields.deactivated_at = null;
} else if (updatedFields.isActivated === false) {
updatedFields.deactivated_at = newDateNow();
updatedFields.activated_at = null;
}
resolve(updatedFields)
});
await Promise.all([other]);
CodePudding user response:
Promise.all
takes an array of promises!- Use promise convention to resolve or reject it.
const other = new Promise(function(resolve, reject) {
updatedFields.last_login_at = newDateNow();
if (updatedFields.isActivated) {
updatedFields.activated_at = newDateNow();
updatedFields.deactivated_at = null;
} else if (updatedFields.isActivated === false) {
updatedFields.deactivated_at = newDateNow();
updatedFields.activated_at = null;
}
resolve(updatedFields);
});
await Promise.all([other]);