繁体   English   中英

在 async.each 回调之前等待承诺

[英]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 永远不会发生并且回调似乎在连接完成运行之前发生。 Connect 成功返回了一个承诺,因为这

router.get('/topics', async function(req, res) {
  console.log('in get');
  const data = await connect(req.body.command);
  await res.send(data);
});

工作正常。 但是包含 async.each 来运行多个命令似乎坏了。 我知道这是我如何调用 async.each 回调函数的问题,但研究并没有说明我应该如何调用它。 等待承诺后是否可以使用.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);
  })
};

虽然您可以继续花更多时间让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 });
  }
})

查看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);
  });
}

如果这仍然不适合您,请随时发表评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM