【发布时间】:2018-10-20 21:04:59
【问题描述】:
我正在尝试使用一个使用 Promise 的回调函数构建的 API。
为了测试它,我创建了这三个函数:
this.functionResolve = (data) => console.log('resolved: ' + data)
this.functionError = (data) => console.log('error: ' + data)
this.functionSucess = (data) => console.log('success: ' + data)
如果使用正常的回调函数,一切正常,我得到两个日志。 (解决和错误/成功取决于 cardBin 通知)
PagSeguroDirectPayment.getBrand({
cardBin: "000000",
complete: this.functionResolve,
success: this.functionSucess,
error: this.functionError
});
为了将它转换为承诺,我最终得到了这个:
this.promisifyCallback = function() {
return new Promise((resolve, _success, _error) => {
PagSeguroDirectPayment.getBrand({
cardBin: "000000",
complete: resolve,
success: _success,
error: _error
});
});
}
当我调用this.promisifyCallback().then(this.functionResolve, this.functionSucess, this.functionError) 时,只会出现解析日志。
如果有人想检查,PagSeguroDirectPayment 对象可在以下位置获得:PagSeguro API
【问题讨论】:
-
Promiuses 有两个回调,而不是三个。没有单独的
success回调的概念。 -
您需要调用resolve或reject来将数据作为thenable返回。然后使用 .then 进行处理。
标签: javascript callback promise