【问题标题】:Promise not firing on all functions承诺不会触发所有功能
【发布时间】: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


【解决方案1】:

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 来获得 complete 行为(在最新的环境中,或使用 polyfill - finally 是最近添加的) .

当我调用this.promisifyCallback().then(this.functionResolve, this.functionSucess, this.functionError) 时,只会出现解析日志。

你会这样使用它:

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”)。 “拒绝”意味着失败。 “解决”意味着解决或拒绝。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-13
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多