es6-promise:承诺httpntlm模块

rak*_*btg 2 node.js promise async-await es6-promise

我想让httpntlm模块返回一个promise,它通过回调实现。

这是带有回调的工作版本:

httpntlm.get({
  url,
  username: 'username',
  password: 'banana'
}, 
function (err, resx){
  if(err) console.log(err);
  else {
    console.log(resx.headers);
    console.log(resx.body);
  }
});
Run Code Online (Sandbox Code Playgroud)

这是我试图使其兑现承诺的方式:

promisify(httpntlm.post(config, (error, response) => {
  if (error) return errro
  return response
}))
.then(res => console.log(res))
.catch(err => console.log(err))
Run Code Online (Sandbox Code Playgroud)

但是promisify版本返回错误:

UnhandledPromiseRejectionWarning:TypeError [ERR_INVALID_ARG_TYPE]:“原始”参数必须为Function类型。接收类型未定义

我想念什么?谢谢

Tom*_*lak 6

这就是文档所说的util.promisify

util.promisify(original)

  • 原版的 <Function>
  • 返回值: <Function>

作为错误消息状态

“原始”参数必须为Function类型,收到的类型为undefined

你做了什么:

promisify(httpntlm.post(config, (error, response) => {
  if (error) return error
  return response
}))
Run Code Online (Sandbox Code Playgroud)

您已经调用了该函数。而httpntlm.post作为一个异步函数,它没有返回。

您应该已经传递了函数:

var httpntlmPostAsync =  promisify(httpntlm.post);

// if `post` depends on `this`
var httpntlmPostAsync =  promisify(httpntlm.post.bind(httpntlm));
Run Code Online (Sandbox Code Playgroud)

就这样。

换句话说,promisify不要为您调用函数,也不要对正在运行的函数调用施加任何魔力。它使新功能的行为有所不同。

httpntlmPostAsync({
  url: 'url',
  username: 'username',
  password: 'banana'
})
.then(res => console.log(res))
.catch(err => console.log(err))
Run Code Online (Sandbox Code Playgroud)

或者,如果您更喜欢:

async function foo() {
  try {
    var res = await httpntlmPostAsync({
      url: 'url',
      username: 'username',
      password: 'banana'
    });
    console.log(res);
  } catch (err) {
    console.log(err);
  }
}
Run Code Online (Sandbox Code Playgroud)

要实现多种功能,您可以使用以下方法:

['get', 'post', 'etc'].forEach(method => 
    httpntlm[method + 'Async'] = promisify(httpntlm[method].bind(httpntlm))
);
Run Code Online (Sandbox Code Playgroud)

在这之后,httpntlm.getAsynchttpntlm.postAsync等可供选择。