简体   繁体   English

如何在async / await格式中处理多个args的回调函数?

[英]How to handle multiple args of callback function in async/await format?

In shelljs, the exec function has 3 arguments in callback (err, stdout, stderr) . 在shelljs中,exec函数在回调中有3个参数(err, stdout, stderr) When using this in async/await by promisify(shelljs.exec) , I'm not able to catch the stderr ? 当在promisify(shelljs.exec) async/await使用它时,我无法捕获stderr

const { promisify } = require('util'),
  shellExec = promisify(shelljs.exec);

....

// in the function

try {
 variableName = await shellExec('some valid shell command', {});

 return variableName;
}
catch (err) {
  console.log(err);
}

If shelljs exec return code 0 ie valid response it works fine, but when the the command is invalid, it returns 1. 如果shelljs exec返回代码0即有效响应它工作正常,但是当命令无效时,它返回1。

I'm not able to get the stderr . 我无法得到stderr

I am assuming you want the value of stderr to output while also using async/await. 我假设你想要stderr的值输出,同时也使用async / await。 Something like this might be of use: 这样的东西可能有用:

var shelljs = require('shelljs');

async function promiseExec(input) {
  return new Promise((resolve, reject) => {
    let { err, stdout, stderr } = shelljs.exec(input);
    shelljs.exit(1);
    if(stdout === "") reject(stderr);
    resolve(stdout);
  })
}

async function main () {
  let result = await promiseExec('dir');
  console.log(result);
}

main();

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

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