-----补充
var promises = [1,2,3].map(function (id) {
return setTimeout(()=>{console.log(id)},1000);
});
Promise.all(promises).then(function (posts) {
console.log('all r')
}).catch(function(reason){
});
// 输出 'all r', 1, 2, 3
ajax 的循环依赖调用可以这么写,接住异步函数
function ajax1 () {
return new Promise(function (resolve, reject){
console.log("执行:ajax1,执行2s")
setTimeout(()=>{resolve('ajax1');},2000);
});
}
function ajax2 () {
return new Promise(function (resolve, reject){
console.log("执行:ajax2,执行1s")
setTimeout(()=>{resolve('ajax2');},1000);
});
}
function ajax3 () {
return new Promise(function (resolve, reject){
console.log("执行:ajax3,执行3s")
setTimeout(()=>{resolve('ajax3');},3000);
});
}
function run (req) {
var it = generator(req); ;
function* generator(arr=[]) {
try {
for(let i of arr){
yield i();
}
} catch (e) {
console.log(e);
}
};
function go(result) {
if (result.done){
console.log('结束')
return result.value;
}
return result.value.then(function (value) {
return go(it.next());
}, function (error) {
return go(it.throw(error));
});
}
go(it.next());
}
run([ajax1,ajax2,ajax3]);