我想让httpntlm模块返回一个诺言,该诺言通过回调实现。

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

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


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

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


但是promisify版本返回错误:


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


我想念的是什么?谢谢

最佳答案

这就是docs say to util.promisify的含义:


util.promisify(original)


原始<Function>
返回值:<Function>



作为错误消息状态


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


你做了什么:

promisify(httpntlm.post(config, (error, response) => {
  if (error) return error
  return response
}))


您已经调用了该函数。而且httpntlm.post是一个异步函数,它不返回任何内容。

您应该已经传递了函数:

var httpntlmPostAsync =  promisify(httpntlm.post);

// if `post` depends on `this`
var httpntlmPostAsync =  promisify(httpntlm.post.bind(httpntlm));


就这样。

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

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


或者,如果您更喜欢:

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




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

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


之后,httpntlm.getAsynchttpntlm.postAsync等可用。

09-20 23:58