我试图将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 回答
我想通了,BlueBird想警告你,一个拒绝()调用已被解雇,但你没有 grab 它 . 所以我用...
所以要修复,请执行以下两项操作之一:将.catch()添加到调用的末尾,或从promise中删除reject(err) .