Promise基础使用(单任务)
var getData = function (link) {
var deferred = Q.defer();
request(link,function (error,response,body) {
if (!error && response.statusCode == 200) {
deferred.resolve(body);
} else {
deferred.reject(error);
}
});
return deferred.promise;
};
var onSuccess = function (data) {
console.log(data);
}
var onFail = function (data) {
console.log(err);
}
getData(link).then(onSuccess);
Promise多任务串行处理
var fun2 = function(result) {
console.log(result);
return result+' fun2 ';
}
var fun3 = function(result) {
console.log(result);
return result+' fun3 ';
}
var cb = function(result) {
console.log(result);
}
var funs = [fun1,fun2,fun3,cb];
// 第一种方式:手动链接
Q('hello').then(fun1).then(fun2).then(fun3).then(cb);
// 第二种方式:动态链接
var result = Q('hello');
funs.forEach(function(func){
result = result.then(func);
});
// 第三种方式:精简后的动态链接
funs.reduce(function(prev,current){
return prev.then(current);
},Q('hello'));
promise多任务并行处理
var fun2 = function (data) {
var defer = Q.defer();
setTimeout(function(){
defer.resolve(data+" fun2");
},1000);
return defer.promise;
}
var fun3 = function (data) {
var defer = Q.defer();
setTimeout(function(){
defer.resolve(data+" fun3");
},1000);
return defer.promise;
}
var cb = function (param1,param2,param3) {
console.log(param1);
console.log(param2);
console.log(param3);
}
Q.all([fun1("test1"),fun2("test2"),fun3("test3")]).spread(cb);
原文链接:https://www.f2er.com/note/422678.html