未处理的拒绝错误与Ajax蓝鸟承诺包装



我正在尝试将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想要警告你一个reject()调用已经被触发,但是你没有捕捉到它。所以我用的是…

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

所以要修复,做两件事之一:将.catch()添加到调用的末尾,或者从promise中删除拒绝(err)

最新更新