解决多个异步操作嵌套问题

JavaScript Promise

用Promise解决多个异步操作嵌套问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let ansyFun = function(count, wait){
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(count, new Date());
resolve(count+1);
}, wait);
});
}

let promise = new Promise(function(resolve, reject) {
resolve(1);
});

promise.then(data => {
return ansyFun(data, 1000);
}).then(data => {
return ansyFun(data, 1000);
}).then(data => {
return ansyFun(data, 2000);
});

用Promise+async解决多个异步操作嵌套问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let ansyFun = function(count, wait){
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(count, new Date());
resolve(count+1);
}, wait);
});
}

async function asyncFun(){
let count = 1;
count = await ansyFun(count, 1000);
count = await ansyFun(count, 1000);
count = await ansyFun(count, 2000);
}
asyncFun();