【问题标题】:Unhandled rejection error with Ajax Bluebird promise wrapperAjax Bluebird 承诺包装器未处理的拒绝错误
【发布时间】:2016-09-12 16:20:24
【问题描述】:

我正在尝试将 Ajax 包装到 Bluebird Promise 包装器中,但我收到了:

错误:未处理的拒绝(此处为堆栈跟踪...)

wrapper1.js

let fetch = require('./wrapper2');

function requestWeb(type, url, data) {
    return new Promise(function(resolve, reject) {
        url = config.serverUrl + url.trim();

        let options = {
            type: type,
            data: data ? JSON.stringify(data) : null,
            dataType: 'json',
            contentType: 'application/json',
            crossDomain: true,
            timeout: 15000,
            xhrFields: { withCredentials: true }
        };

        fetch(url, options)
            .then(data => {
                resolve(data);
            })
            .catch(err => {
                console.log('web api error: ' + err.message);
                notify('Please check your interet connection');
                reject(err);
            });
    });
}

wrapper2.js

import Promise from 'bluebird';

export default function(url, options) {
    return new Promise(function(resolve, reject) {
        $.ajax(url, options)
            .done((result) => {
                resolve(result);
            })
            .fail((xhr, err) => {
                let proxy = new Error();
                proxy.message = err || 'error is null';
                proxy.name = 'ajax error';

                reject(proxy);
            });
    });
}

请注意 Bluebird requires different error object 拒绝()。

【问题讨论】:

  • 这是一种反模式。 jQuery $.ajax 返回一个 then-able。你不需要将它包装在 Promise 中。
  • 根据我的理解,即使失败也会在 Ajax 中调用
  • 使用then 代替donefail
  • 那么你如何在失败时停止运行

标签: javascript jquery ajax asynchronous promise


【解决方案1】:

我想通了,BlueBird 想警告你一个 reject() 调用已被触发,但你没有接听它。所以我用...

requestWeb(type, url, data).then((result)=>{});

因此,要解决此问题,请执行以下两项操作之一:将 .catch() 添加到调用末尾,或从 promise 中删除 reject(err)。

【讨论】:

  • 不,不要删除reject(),这只是在抑制错误。
  • 我在控制台记录错误,所以我们可以看到错误,也将错误发送给管理员,但用户看不到错误。然后在应用程序的大约 100 个地方我们不需要 .catch() 块。
猜你喜欢
  • 2017-06-08
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
相关资源
最近更新 更多