在async.each中的回调之前等待promise

时间:2018-10-26 15:52:23

标签: javascript callback async-await es6-promise async.js

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

1 个答案:

答案 0 :(得分:1)

尽管您可以继续花更多的时间来使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);
  });
}

如果仍然无法解决问题,请随时发表评论。