ES6 Promise 并行执行和顺序执行
生活随笔
收集整理的這篇文章主要介紹了
ES6 Promise 并行执行和顺序执行
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.Promise.all 并行執行promise
getA和getB并行執行,然后輸出結果。如果有一個錯誤,就拋出錯誤
/*** 每一個promise都必須返回resolve結果才正確* 每一個promise都不處理錯誤*/const getA = new Promise((resolve, reject) => {//模擬異步任務setTimeout(function(){resolve(2);}, 1000) }) .then(result => result)const getB = new Promise((resolve, reject) => {setTimeout(function(){// resolve(3);reject('Error in getB');}, 1000) }) .then(result => result)Promise.all([getA, getB]).then(data=>{console.log(data) }) .catch(e => console.log(e));getA和getB并行執行,然后輸出結果??偸欠祷豶esolve結果
/*** 每一個promise自己處理錯誤*/const getA = new Promise((resolve, reject) => {//模擬異步任務setTimeout(function(){resolve(2);}, 1000) }) .then(result => result) .catch(e=>{})const getB = new Promise((resolve, reject) => {setTimeout(function(){// resolve(3);reject('Error in getB');}, 1000) }) .then(result => result) .catch(e=>e)Promise.all([getA, getB]).then(data=>{console.log(data) }) .catch(e => console.log(e));2.順序執行promise
先getA然后getB執行,最后addAB
- 2.1 方法一——連續使用then鏈式操作
- 2.2 方法二——使用promise構建隊列?
- 2.3方法三——使用async、await實現類似同步編程
3. 總結
實現異步隊列函數的三種方式
方法一——連續使用then鏈式操作
方法二——使用promise構建隊列
方法三——使用async、await實現類似同步編程,async函數內部實現同步
總結
以上是生活随笔為你收集整理的ES6 Promise 并行执行和顺序执行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: webstorm 破解
- 下一篇: 利用协议代理实现导航控制器UINavig