Reputation: 83
I am writing a function in my server to return data from client A to client B at the time client B is sending request. When function is called, my server send request to client A and then client A send data back to server. The problem is how to make this function wait until server received data from client A.
I already use setTimeout
and it worked for me but it not flexible
//the code for receiving data from client A is written in another file
socketA.emit('getData', JSON.stringify(json));
//I want my function will stopping here
socketB.emit('sendData', somedata);
This is my code for receiving data from client
socket.on('getData', (data) =>{
storage_data = data;
});
I expect there is a way to stop my function without using setTimeout
or if I make something wrong, please tell me.
Thanks.
Upvotes: 1
Views: 3165
Reputation: 855
This can be done with async/await syntax
socket.on('getData', async (data) =>{
storage_data = await data;
});
For reference: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
Upvotes: 0
Reputation: 105
I think Promise is a definitely way (I not sure, but just give it a try).This Asynchronous in NodeJS might be helpful.
Upvotes: 2