Ajax Bluebird承诺包装器的未处理拒绝错误

时间:2016-09-12 16:20:24

标签: javascript jquery ajax asynchronous promise

我正在尝试将Ajax包装成Bluebird承诺包装器,但是我正在接收:

  

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

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

1 个答案:

答案 0 :(得分:0)

我明白了,BlueBird想要警告你,一个拒绝()调用已被解雇,但你没有抓住它。所以我正在使用......

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

所以要修复,请执行以下两项操作之一:将.catch()添加到调用的末尾,或从promise中删除reject(错误)。