應用場景:有多個異步的方法,需要同步化序列,這時候一般的處理是定義一個方法,利用 async 將其 一個一個添加 await 然后執行,也可以利用 Promise.all 來處理,相比之下,使用 Promise.all([ ]) 的方法,可以更加高效的執行,能夠快速的去序列化,但是使用這個方法的劣勢就是,一旦有異常了 promise 就會跳出,進而進行 catch 的回調,這樣異常之后 promise.all 里邊的代碼語句就不會執行了;例如:
async function test () { console.log( new Date().getSeconds(),'a'); await rej(1000); await rej(2000); await rej(3000); console.log( new Date().getSeconds(),'b'); }; async function test1 () { console.log( new Date().getSeconds(),'c'); await Promise.all([rej(1000), rej1(2000), rej2(3000)]); console.log( new Date().getSeconds(),'d'); }; var rej = (time) => new Promise((resolve, reject) => { setTimeout(() => resolve('reject'), time); }); var rej1 = (time) => new Promise((resolve, reject) => { setTimeout(() => reject('reject'), time); }); var rej2 = (time) => new Promise((resolve, reject) => { setTimeout(() => resolve('reject'), time); }); test(); test1();