• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

26
Views
Creating a Promise

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
about 2 months ago ·

Juan Pablo Isaza

2 answers
Answer question

0

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.

enter image description here

 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]);
about 2 months ago · Juan Pablo Isaza Report

0

  1. Promise.all takes an array of promises!
  2. 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]);
about 2 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.