异步编程:When.js快速上手

var api = 'http://qgy18.imququ.com/file/when/d.php?cb=?';

var getData = function() {
var deferred = when.defer(); $.getJSON(api, function(data){
deferred.resolve(data[0]);
}); return deferred.promise;
} var getImg = function(src) {
var deferred = when.defer(); var img = new Image(); img.onload = function() {
deferred.resolve(img);
}; img.src = src; return deferred.promise;
} var showImg = function(img) {
$(img).appendTo($('#container'));
} getData()
.then(getImg)
.then(showImg);
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="http://qgy18.imququ.com/file/when/when.js"></script>
<div id="output"></div>
<script>
function run() {
var deferred = when.defer();
var start = 1;
var end = 100; (function() {
if (start <= end) {
deferred.notify(start);
start++;
setTimeout(arguments.callee, 50);
} else {
deferred.reject('time out!');
}
})(); return deferred.promise;
} /**
* then有三个参数,分别是onFulfilled、onRejected、onProgress,通过这三个参数,就可以指定上一个任务在resolve(完成状态)、reject(失败状态)和notify(执行状态)时该如何处理
*/
run().then(undefined,
function(reason) {
alert(reason);
}, function(s) {
document.getElementById('output').innerHTML = s + '%';
}
);
</script>
</body>
</html>

when.all

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="http://s0.qhimg.com/lib/jquery/183.js"></script>
<script src="http://qgy18.imququ.com/file/when/when.js"></script>
<div id="container"></div>
<script>
var getData = function() {
var deferred = when.defer();
deferred.resolve(["http:\/\/st.imququ.com\/uploads\/2011\/07\/IMAG0038_2.jpg","http:\/\/st.imququ.com\/uploads\/2011\/07\/wewewewe_1.jpg","http:\/\/st.imququ.com\/uploads\/2011\/07\/IMAG0014_2_1.jpg"]);
return deferred.promise;
} var getImg = function(src) {
var deferred = when.defer();
var img = new Image();
img.onload = function() {
//deferred.resolve(img);
};
img.src = src;
deferred.resolve(img);
return deferred.promise;
} var showImgs = function(imgs) {
console.log(imgs);
$(imgs).appendTo($('#container'));
} var getImgs = function(data) {
var deferreds = [];
for(var i = 0; i < data.length; i++) {
deferreds.push(getImg(data[i]));
}
return deferreds;
}
// when.all接受一个promise数组,返回promise,这个promise会在promise数组中每一个promise都resolve之后再resolve
when.all(getData().then(getImgs)).then(showImgs);
</script>
</body>
</html>

when.settle

var promise1 = function() {
var deferred = when.defer();
setTimeout(function() {
console.log('A')
deferred.reject('A');
}, 2000);
return deferred.promise;
}; var promise2 = function() {
var deferred = when.defer();
setTimeout(function() {
console.log('B')
deferred.resolve('B');
}, 1000);
return deferred.promise;
}; var f = function(result) {
console.log(result);
} when.settle([promise1(), promise2()]).then(f); // [promise1(), promise2()]无序 then有序
05-02 20:31