更新
新增Promise.timeout方法,检测task执行超时并且自动reject
使用
Promise.timeout(f1(), 2000).then(f2, function () {
alert("timeout");
}).wait(5000).then(f3);
function f1() {
var promise = Promise();
setTimeout(function () {
console.log(1);
promise.resolve("from f1");
}, 1500)
return promise;
}
function f2() {
var promise = Promise();
setTimeout(function () {
console.log(2);
promise.resolve();
}, 1500)
return promise;
}
function f3() {
var promise = Promise();
setTimeout(function () {
console.log(3);
promise.resolve();
}, 1500)
return promise;
}
AJAX
function xhr(options) {
var promise = Promise(),
req = new XMLHttpRequest();
req.open(options.method || 'GET', options.url, true);
// Set request headers if provided.
Object.keys(options.headers || {}).forEach(function (key) {
req.setRequestHeader(key, options.headers[key]);
});
req.onreadystatechange = function (e) {
if (req.readyState !== 4) {
return;
}
if ([200, 304].indexOf(req.status) === -1) {
promise.reject('Server responded with a status of ' + req.status);
} else {
promise.resolve(e.target.result);
}
};
req.send(options.data || void 0);
return promise;
}
使用:
xhr({ url: "xxx.php?a=xxx" }).then(function (msg) {
})
当然,promise支持等待N个AJAX都完成之后进行回掉:
Promise(xhr({ url: "a.php?c=xxx" }), xhr({ url: "b.php?d=xxx" })).then(function () {
})
上面的写法的Promise.when的缺省形式。
Promise.timeout with AJAX
这里需要思考的是:timeout是属于AJAX还是属于Promise?
如果属于AJAX,那么就有下面这种形式:
xxx.ajax("xxx.php", {
method: "GET",
data: null,
onSuccess: function () { },
onTimeout: function () { },
timeout: 30000
});
如果属于Promise:
Promise.timeout(xhr({ url: "xxx.php" }), 30000).then(
function () { },
function () { }
)
更多
有关promise更多信息你可以访问:
getting started with Promise.js(总)
你可以点击这里下载最新版promise.js。