[英]await promise before callback in async.each
router.post('/runCommand', async function(req, res){
let results = [];
async.each(req.body.requests, async function(request, callback){
const data = await connect(request.command)
await results.push(data);
await callback(null);
}, function(err){
if (!err) {
res.send(202, results)
}
})
})
Res.send is never taking place and callback seems to happen before connect is finished running. Res.send 永远不会发生并且回调似乎在连接完成运行之前发生。 Connect is succesfully returning a promise because this Connect 成功返回了一个承诺,因为这
router.get('/topics', async function(req, res) {
console.log('in get');
const data = await connect(req.body.command);
await res.send(data);
});
works fine.工作正常。 But including the async.each to run multiple commands seems broken.但是包含 async.each 来运行多个命令似乎坏了。 I know this is an issue with how I'm calling async.each callback function but research hasn't availed how I should be calling it.我知道这是我如何调用 async.each 回调函数的问题,但研究并没有说明我应该如何调用它。 Is it possible to use a .then()
after awaiting a promise?等待承诺后是否可以使用.then()
?
function connect(command){
return new Promise(function(resolve) {
let host = {
server: {
host: "host",
port: "port",
userName: "user",
password: config.Devpassword
},
commands: [ command ]
};
var SSH2Shell = require ('ssh2shell'),
//Create a new instance passing in the host object
SSH = new SSH2Shell(host),
//Use a callback function to process the full session text
callback = function(sessionText){
console.log(sessionText)
resolve(sessionText);
}
SSH.connect(callback);
})
};
While you could continue to sink more time into getting async.each()
to work, I recommend just dropping it and going exclusively with the async
/ await
syntax which simplifies your code a lot:虽然您可以继续花更多时间让async.each()
工作,但我建议您放弃它并专门使用async
/ await
语法,这可以大大简化您的代码:
router.post('/runCommand', async function (req, res) {
try {
const results = await Promise.all(
req.body.requests.map(({ command }) => connect(command))
);
res.send(202, results);
} catch ({ message, stack }) {
res.send(500, { error: message, stack });
}
})
Looking at the ssh2shell
documentation, I think your connect
function could be improved as well for better readability and error handling:查看ssh2shell
文档,我认为您的connect
功能也可以改进,以获得更好的可读性和错误处理:
const SSH2Shell = require('ssh2shell');
function connect (command) {
return new Promise((resolve, reject) => {
const host = {
server: {
host: 'host',
port: 'port',
userName: 'user',
password: config.Devpassword
},
commands: [command]
};
//Create a new instance passing in the host object
const SSH = new SSH2Shell(host);
SSH.on('error', reject);
SSH.connect(resolve);
});
}
Please feel free to comment if this still doesn't work for you.如果这仍然不适合您,请随时发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.