0

I am currently new to node.js and I actually implementing chat system in my ongoing project , frontend is angular and using node.js for socket functionality.

Right now I am stuck with one issue that I am not getting desired value while returning in function which calls external api using "request" in node.js. I am calling same function in socket on event and want record id for my purpose.

Below is code for calling external api which is located on php server from node.js.

const insertChatData = (body) => {
            const url = adminUrl + 'chatSystem';
            let recordId;
            request.post({
                url,
                headers,
                body,
                json:true } , (error , res) => {
                    recordId = res.body.recordId // getting value here correctly 
                }
            )
            console.log(recordId , 'boo') // getting undefined here  
            return recordId // returned undefined
        }

    

Below is the code for socket event where I am trying to call the required fuction in order to get record id and I want emit back that to my client which is angular .

socket.on("sendingMessage2", (msgData, hsocId) => {
   //some coding stuff....
   let recordId = insertChatData(msgData) // gtting undefined

   });


 Please let me know what is the correct approch in order to get and return the recordId back to calling socket event. Thanks.
chgav007
  • 85
  • 1
  • 13
  • use one of the usual asynchronous coding patterns - callbacks,or the easier to use callbacks called Promises, or the easier to use Promises called async/await – Jaromanda X Aug 30 '22 at 06:26

1 Answers1

0

Nodejs is asynchronous because of which it is undefined. The console is executed before the API call. To make it work you can use async-await to make your code look synchronous.

const insertChatData = async (body) => {
      const url = adminUrl + 'chatSystem';
      const response = await request.post({
            url,
            headers,
            body,
            json:true })
      const recordId = response.data.recordId;
      console.log(recordId , 'boo') 
      return recordId 
}

socket.on("sendingMessage2", async(msgData, hsocId) => {
   //some coding stuff....
   let recordId = await insertChatData(msgData) 
});
architjn
  • 1,397
  • 2
  • 13
  • 30
Drashti Kheni
  • 1,065
  • 9
  • 23