-
Notifications
You must be signed in to change notification settings - Fork 52
Promise用法2
LYF edited this page Jun 4, 2016
·
2 revisions
多个ajax之间的嵌套
// 首先用Promise包一层
var getData = function(options){
return new Promise(function(resolve,reject){
options.type = options.type || "POST";
options.data = options.data || "";
options.dataType = options.dataType || "json";
options.contentType = options.contentType || 'application/json';
options.timeout = options.timeout || 8000;
options.success = function(result){
var data = result.data;
console.log(result.state);
if( data && result.state === "SUCCESS" ){
resolve(data);
}else{
result.url = options.url;
reject(result);
}
}
options.error = function(error){
error.url = options.url;
reject(error);
}
$.ajax(options);
})
}
getData({
url:"http://xxx.xxx.xxx.xxx/v1/getalllist",
type:"GET"
}).then(function(result){
// 处理第一个异步任务的结果
// 组装第二个异步任务需要的参数开始
console.log(result);
var sids = Object.keys(result);
sids.sort(function(s1,s2){
return s2 - s1;
})
var allSKUList = [];
sids.forEach(function(cid){
allSKUList.push.apply(allSKUList,result[cid]);
})
console.log(allSKUList);
// 组装第二个异步任务需要的参数完成
// 执行第二个异步任务
return getData({
url:"http://xxx.xxx.xxx.xxx/v1/getfullsku",
data:JSON.stringify({
sids:allSKUList
})
});
}).then(function(result){
// 处理第二个异步任务的结果
console.log(result);
// ...
}).catch(function(error){
console.log(error);
})