1.使用场景
有异步操作的时候,会使用Promise对这个操作进行封装,防止套娃
2.基本结构
处理形式1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| new Promise((resolve, reject) => { setTimeout(() => { resolve(data.id); reject(err); }, 1000); }) .then((data) => { }) .catch((err) => { });
|
处理形式2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| new Promise((resolve, reject) => { setTimeout(() => { resolve(data.id); reject(err); }, 1000); }).then( (data) => { }, (err) => { } );
|
3.两种简写
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
| new Promise((resolve, reject) => { setTimeout(() => { resolve("Jamie"); }, 1000); }) .then((data) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(data.toLocaleLowerCase()); }, 1000); }); }) .then((data) => { console.log(data); data += " Wang"; return Promise.resolve(data + " Chi"); }) .then((data) => { console.log(data); return data + " Jie"; }) .then(data => console.log(data));
|
4.多异步操作写法
1 2 3 4 5 6 7 8 9 10 11 12
| Promise.all([ new Promise((resolve, reject) => { resolve('res1') }), new Promise((resolve, reject) => { resolve('res2') }), ]).then((results) => { console.log(results); })
|
重要单词
sync
synchronization [ˌsɪŋkrənaɪ’zeɪʃ(ə)n] 同步
async
asynchronization 异步