Function returns the object before, the findById() fill it with the required data

42 Views Asked by At

So, the problem is with the javascript basics I think.

'use strict';

module.exports = function accountWithSingleOrganisation(Account) {

  Account.accountWithSingleOrganisation = function(accessToken, cb) {

    accessToken.user(function(err, user) {
      if (err) return cb(err);

      let accData = {};
      user.role(async (err, role) => {
        if (err) return cb(err);

        for (let it in role.scopes) {
          if (role.scopes[it].account == null) break;
          console.log('1');
          await Account.findById(role.scopes[it].account, (err, account) => {
            if (err) return cb(err);

            console.log('2');

            // Assigning Data Here
            accData = Object.assign(accData, {                      
              name: account.name,
              id: account.id,
            });
          });
        };
        console.log(accData);
        return cb(null, accData);
      });
    });
  };
};

In my program I don't know how to use async await properly, due to which the for loop is executed and function returns the accData even before the assignment of data. Can you tell me how to use async await, or any other way through which, my function first assigns object it's data and, then return the data.

1

There are 1 best solutions below

0
On

We, can take a response at place where we used await, and then push the data. That way it is wrking.