'How to stop a nodeJS Api res.send(response) from returning to a request before an Async functions inside it have returned?
I am making a React and Node JS app which accepts some parameters from user and based on that the Node backend SSH into a server executes some commands and return the values to the front end.
The problem is on the NodeJS script I am using simple-ssh library to log in to remote server and execute the commands to get values from the server but the api returns to the front end before the Node finished this async call. I have used async/await to solve the issue but still getting the same problem.
app.get('/data', async(req,res) =>{
const response = await ssh.exec('ls /home/user', {
out: function (stdout) {
response = stdout;
console.log("recieved response");
console.log(response)
},
err: function (stderr) {
console.log(stderr);
},
exit: function (code) { console.log(code); }
}).start();
console.log('fetching done')
res.send(response)
})
out put looks like this
fetching done
response recieved
project
school
new folder
so by the time the file lists in the /home/user returns , the res.send(response) has already executed and returns empty value to front end.
Is there any way to stop the res.send(response) executing before the list has done fetching
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
