我正在尝试使用通过使用 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({
卡宾:“000000”,
完成:this.functionResolve,
成功:this.functionSuccess,
错误:this.functionError
});
为了将其转换为 promise ,我最终得到了以下结果:
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
最佳答案
Promise 执行器函数(您传递给 new Promise
的回调)仅接收两个参数,而不是三个:resolve
(用于解析项目) 和 reject
(拒绝它)。 (您可以随意调用它们;这些都是常用的名称。)
这意味着您当前的代码:
- 请求完成后,无论是否有效,您都会进行解析,因为
success:resolve
- 当请求成功时(因为
success: _success
),您将拒绝(除非该 API 首先调用complete
处理程序; promise 只能被解决或拒绝一次) - 您的
_error
参数将始终为未定义
相反:
this.promisifyCallback = function() {
return new Promise((resolve, reject) => {
PagSeguroDirectPayment.getBrand({
cardBin: "035138",
//complete: ,
success: resolve,
error: reject
});
});
}
当消费 promise 时,您可以通过使用.finally
(在最新环境中,或使用一个polyfill——终于
是最近添加的)。
When I call
this.promisifyCallback().then(this.functionResolve, this.functionSucess, this.functionError)
only the resolve log appears.
你可以像这样使用它:
this.promisifyCallback()
.then(this.functionSucess, this.functionError)
.finally(this.functionResolve); // See ¹
或
this.promisifyCallback()
.then(this.functionSucess)
.catch(this.functionError)
.finally(this.functionResolve); // See ¹
¹ Promise 语言中的“Resolve”意思是“成功完成”(有时也使用“fulfill”)。 “拒绝”就是失败的意思。 “解决”的意思是解决或拒绝。
关于javascript - promise 不会触发所有功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275508/