ram
ram

Reputation: 210

not able to make the code await using 'await' till a function completes

I'm calling a local function, it has to wait for that local function's result to continue further.

this is my local function

var Messagehome =  (req, res) => {
  user.find().exec(async (err, user) => {
    if (err) return res.json(err);
    let p = await getfulluser(req.User._id);

    list = user.filter((u) => u._id != req.User._id);

    console.time("time1");
    for (let i = 0; i < p.messages.length; i++) {
      for (let e = 0; e < list.length; e++) {
        if (list[e]._id.equals(p.messages[i]._id)) {
          list.splice(e, 1);
          break;
        } else {
          console.log(list[e].name);
          list[e].password = undefined;
        }
      }
    }
    console.timeEnd("time1");
    return res.json(list), list;
  });
};

exports.Messagehome = Messagehome;

I want to use Messagehome in this function. It has to wait for Messagehome to continue 'for loop'.I tried await, but it didn't work

exports.refreshfind = async (req, res) => {
  let { id } = req.body;

  if (list) {
    console.time("TIME   1");
    for (let e = 0; e < list.length; e++) {
      if (list[e]._id.equals(id)) {
        list.splice(e, 1);
        res.json(list);
        console.timeEnd("TIME   1");
        break;
      }
    }
  }
  if (!list) {
    console.time("TIME    2");
    Messagehome();
    for (let e = 0; e < list.length; e++) {
      if (list[e]._id.equals(id)) {
        list.splice(e, 1);
        res.json(list);
        console.timeEnd("TIME    2");
        break;
      }
    }

  }
};

I'm getting this error

(node:13396) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
    at exports.refreshfind (D:\message\backend\controllers\message.js:58:30)
    at Layer.handle [as handle_request] (D:\message\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\message\backend\node_modules\express\lib\router\route.js:137:13)
    at D:\message\backend\controllers\user.js:94:5
    at D:\message\backend\node_modules\jsonwebtoken\verify.js:223:12
    at getSecret (D:\message\backend\node_modules\jsonwebtoken\verify.js:90:14)
    at Object.module.exports [as verify] (D:\message\backend\node_modules\jsonwebtoken\verify.js:94:10)
    at exports.isSignedIn (D:\message\backend\controllers\user.js:89:7)
    at Layer.handle [as handle_request] (D:\message\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\message\backend\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\message\backend\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\message\backend\node_modules\express\lib\router\layer.js:95:5)
    at D:\message\backend\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\message\backend\node_modules\express\lib\router\index.js:335:12)
    at next (D:\message\backend\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (D:\message\backend\node_modules\express\lib\router\index.js:174:3)
(node:13396) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13396) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13396) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'User' of undefined
    at D:\message\backend\controllers\message.js:14:35
    at D:\message\backend\node_modules\mongoose\lib\model.js:4599:16
    at D:\message\backend\node_modules\mongoose\lib\utils.js:264:16
    at D:\message\backend\node_modules\mongoose\lib\query.js:4326:11
    at D:\message\backend\node_modules\kareem\index.js:135:16
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
(node:13396) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

It couldn't read 'length' from if( ! list ) in refreshfind.

I tried await for Messagehome and for loop, but it didn't work

 if (!list) {
    console.time("TIME    2");
    Messagehome();
    for (let e = 0; e < list.length; e++) {
      if (list[e]._id.equals(id)) {
        list.splice(e, 1);
        res.json(list);
        console.timeEnd("TIME    2");
        break;
      }
    }

  }
};

Upvotes: 1

Views: 117

Answers (1)

ram
ram

Reputation: 210

I got some solution from live chat room. Since Messagehome(req,res) is defined with req, res, I have to call it in the same way as

Messagehome(req,res)

and this is not going to work

Messagehome()

I found the remaining solution by studying promise. Messagehome must be a promise based function to await when it's called. This is the complete solution

var Messagehome =  (req, res) =>  new Promise((resolve, reject) => {
  user.find().exec(async (err, user) => {
    if (err) return res.json(err);
    let p = await getfulluser(req.User._id);

    list = user.filter((u) => u._id != req.User._id);

    console.time("time1");
    for (let i = 0; i < p.messages.length; i++) {
      for (let e = 0; e < list.length; e++) {
        if (list[e]._id.equals(p.messages[i]._id)) {
          list.splice(e, 1);
          break;
        } else {
          console.log(list[e].name);
          list[e].password = undefined;
        }
      }
    }
    console.timeEnd("time1");
     res.json(list);
     resolve (list)
  });
})

exports.Messagehome = Messagehome;

since Messagehome is promise based function, it's going to wait till that promise completes.So i can get list from Messagehome in refreshfind

exports.refreshfind = async (req, res) => {
  let { id } = req.body;

  if (list) {
    console.time("TIME   1");
    for (let e = 0; e < list.length; e++) {
      if (list[e]._id.equals(id)) {
        list.splice(e, 1);
        res.json(list);
        console.timeEnd("TIME   1");
        break;
      }
    }
  }
  if (!list) {
    console.time("TIME    2");
   await Messagehome(req,res);
    for (let e = 0; e < list.length; e++) {
      if (list[e]._id.equals(id)) {
        list.splice(e, 1);
        res.json(list);
        console.timeEnd("TIME    2");
        break;
      }
    }

  }
};

Now await is going to really wait for me

Upvotes: 1

Related Questions