以setTimeout模拟网络请求的过程
1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| new Promise((resolve, reject) => { setTimeout(() => { resolve("aaa"); }, 1000); }) .then((data) => { console.log(data);
return new Promise((resolve, reject) => { setTimeout(() => { resolve(data + "bbb"); }, 1000); }); }) .then((data) => { console.log(data);
return new Promise((resolve, reject) => { setTimeout(() => { resolve(data + "ccc"); }, 1000); }); }) .then((data) => { console.log(data); });
|
2.new Promise(resolve => resolve(结果))简写为Promise.resolve()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| new Promise((resolve, reject) => { setTimeout(() => { resolve("aaa"); }, 1000); }) .then((data) => { console.log(data);
return Promise.resolve(data + "bbb"); }) .then((data) => { console.log(data);
return Promise.resolve(data + "ccc"); }) .then((data) => { console.log(data); });
|
3.省略Promise.resolve
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| new Promise((resolve, reject) => { setTimeout(() => { resolve("aaa"); }, 1000); }) .then((data) => { console.log(data);
return data + "bbb"; }) .then((data) => { console.log(data);
return data + "ccc"; }) .then((data) => { console.log(data); });
|