Promise数组如下
var createPromise = function(time) {
var promise = ()=>{
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve(time);
}, time*1000)
})
}
return promise
}
var arr = [createPromise(2),createPromise(1),createPromise(3),createPromise(4),createPromise(5)]
async
const asyncFn = async arr => {
for(let item of arr){
let result = await item()
console.log(result)
}
}
asyncFn(arr)
Generator
const Cgenerator = function (arr) {
const fn = function* () {
for(let item of arr){
yield item()
}
}
const gen = fn();
const step = function (nextF) {
let next=nextF()
if (next.done) {
return;
}
if (next.value) {
next.value.then((data) => {
console.log(data)
step(() => { return gen.next(); })
})
}
}
step(() => { return gen.next(); })
}
Cgenerator(arr)
Promise.resolve()
const promiseThen=function(arr){
let res = Promise.resolve()
arr.forEach(item => {
res = res.then(() => {
return item()
}).then((data) => {
console.log(data)
})
});
}
promiseThen(arr)
或
var promiseThen= function(arr) {
arr.reduce(function(prev, next){
return prev.then(function(){
return next()
}).then((data)=>{
console.log(data)
})
}, Promise.resolve())
}
promiseThen(arr)