gpt4 book ai didi

javascript - promise 不会触发所有功能

转载 作者:行者123 更新时间:2023-11-29 17:45:15 27 4
gpt4 key购买 nike

我正在尝试使用通过 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.functionSucess,
错误: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 参数将始终是undefined

相反:

this.promisifyCallback = function() {
return new Promise((resolve, reject) => {
PagSeguroDirectPayment.getBrand({
cardBin: "035138",
//complete: ,
success: resolve,
error: reject
});
});
}

使用 promise 时,您可以通过使用 .finally 获得完整行为(在最新的环境中,或者使用一个 polyfill — finally 最近添加)。

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com