日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

ES6 Promise 并行执行和顺序执行

發布時間:2023/12/10 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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鏈式操作
function getA(){return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(2);}, 1000);}); }function getB(){return new Promise(function(resolve, reject){ setTimeout(function(){resolve(3);}, 1000);}); }function addAB(a,b){return a+b }function getResult(){var obj={};Promise.resolve().then(function(){return getA() }).then(function(a){obj.a=a;}).then(function(){return getB() }).then(function(b){obj.b=b;return obj;}).then(function(obj){return addAB(obj['a'],obj['b'])}).then(data=>{console.log(data)}).catch(e => console.log(e));} getResult();
  • 2.2 方法二——使用promise構建隊列?
function getResult(){var res=[];// 構建隊列function queue(arr) {var sequence = Promise.resolve();arr.forEach(function (item) {sequence = sequence.then(item).then(data=>{res.push(data);return res})})return sequence}// 執行隊列queue([getA,getB]).then(data=>{return addAB(data[0],data[1])}).then(data => {console.log(data)}).catch(e => console.log(e));}getResult();
  • 2.3方法三——使用async、await實現類似同步編程
function getResult(){async function queue(arr) {let res = []for (let fn of arr) {var data= await fn();res.push(data);}return await res }queue([getA,getB]).then(data => {return addAB(data[0],data[1])}).then(data=>console.log(data))}

3. 總結

實現異步隊列函數的三種方式

方法一——連續使用then鏈式操作
方法二——使用promise構建隊列
方法三——使用async、await實現類似同步編程,async函數內部實現同步

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的ES6 Promise 并行执行和顺序执行的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。