So I have this code and I'm trying to understand the async/await syntax in full depth. The below is the Promise version of the code:
function callToolsPromise(req) {
return new Promise((resolve, reject) => {
let pipshell = 'pipenv';
let args = ['run', 'tools'];
req.forEach(arg => {
args.push(arg)
});
tool = spawn(pipshell, args);
tool.on('exit', (code) => {
if (code !== 0) {
tool.stderr.on('data', (data) => {
reject(data);
});
} else {
tool.stdout.on ('data', (data) => {
resolve(JSON.parse(data)):
});
}
});
})
}
I have some python code I want to execute in tools/__main__.py so that's why I'm calling "pipenv".
Here's my attempt to do write it in async/await way (which actually works):
async function callToolsAsync(req) {
let pipshell = 'pipenv';
let args = ['run', 'tools'];
req.forEach(arg => {
args.push(arg)
});
let tool = spawn(pipshell, args);
for await (const data of tool.stdout) {
return data
}
}
But all I did was copy and paste from someone's example where I have for await...
loop.
Therefore I've been trying to rewrite this same code so that I can actually understand it but I've been failing for days now.
Are there any other ways to write this code with async/await way without using the for await...
loop?
Also I have no idea how I can access data except for using the .then
syntax:
callToolsAsync(['GET','mailuser'])
.then(console.log)
How else would I access "data" from resolve(data)
?
Many thanks.
stdout
/stderr
only after theexit
event seems like a very bad idea – Inane