-2

Third console statement executes before the second one when i request to api to get response the other code start executing and i want to prevent this i'm new to javascript., i tryed async-await but i'm doing something wrong..!

app.post('/api', async (req, res) => {  
  console.log(req.body.msg+" -> "+req.body.user+" -> one");    
  options.qs.message=req.body.msg;
  options.qs.uid=req.body.user;    
  let botRespone= await request(options, function (error, response, body) {
    if (error) throw new Error(error);
    console.log(body+" -> two");
    botRespone=body;
  });    
  console.log(botRespone.chatbot+" -> three");    
}); 
  • 1
    You have passed a callback function to `request` and you also have awaited it - use either one of them, not both at the same time. – Yousaf Aug 02 '21 at 07:31
  • 1
    Whats `request`? Does it return a promise, given that it has a callback I'm going to say it doesn't – Liam Aug 02 '21 at 07:31

1 Answers1

1

It's because you're supplying callback function, which doesn't return promise, which is required to work if you want to await it. Thus, removing the callback should solve the problem. Also, be sure that you're using request-promise library, because default request library doesn't return promises.

app.post('/api', async (req, res) => {  
  console.log(req.body.msg+" -> "+req.body.user+" -> one");    
  options.qs.message=req.body.msg;
  options.qs.uid=req.body.user;    
  let botRespone= await request(options);    
  console.log(botRespone.chatbot+" -> three");    
}); 
GAMELASTER
  • 1,071
  • 1
  • 12
  • 23
  • 1
    See https://www.npmjs.com/package/request-promise — Don't use request-promise **or** request. Both have been deprecated. – Quentin Aug 02 '21 at 07:36