亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript異步操作中串行和并行

 更新時間:2021年11月19日 10:34:05   作者:Aaron  
這篇文章主要介紹了JavaScript異步操作中串行和并行,主要內容是寫一下js中es5和es6針對異步函數(shù),串行執(zhí)行和并行執(zhí)行的方案。已經串行和并行結合使用的例子。,需要的朋友可以參考一下

1、前言

本文寫一下jses5es6針對異步函數(shù),串行執(zhí)行和并行執(zhí)行的方案。已經串行和并行結合使用的例子。

2、es5方式

在es6出來之前,社區(qū)nodejs中針對回調地獄,已經有了promise方案。假如多個異步函數(shù),執(zhí)行循序怎么安排,如何才能更快的執(zhí)行完所有異步函數(shù),再執(zhí)行下一步呢?這里就出現(xiàn)了js的串行執(zhí)行和并行執(zhí)行問題。

3、異步函數(shù)串行執(zhí)行

var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];

function async(arg, callback) {
  console.log('參數(shù)為 ' + arg +' , 1秒后返回結果');
  setTimeout(function () { callback(arg * 2); }, 1000);
}

function final(value) {
  console.log('完成: ', value);
}

function series(item) {
  if(item) {
    async( item, function(result) {
      results.push(result);
      return series(items.shift());// 遞歸執(zhí)行完所有的數(shù)據(jù)
    });
  } else {
    return final(results[results.length - 1]);
  }
}

series(items.shift());

4、異步函數(shù)并行執(zhí)行

上面函數(shù)是一個一個執(zhí)行的,上一個執(zhí)行結束再執(zhí)行下一個,類似es6(es5之后統(tǒng)稱es6)中 async 和await,那有沒有類似promise.all這種,所有的并行執(zhí)行的呢?

可以如下寫:

var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];

function async(arg, callback) {
  console.log('參數(shù)為 ' + arg +' , 1秒后返回結果');
  setTimeout(function () { callback(arg * 2); }, 1000);
}

function final(value) {
  console.log('完成: ', value);
}

items.forEach(function(item) {// 循環(huán)完成
  async(item, function(result){
    results.push(result);
    if(results.length === items.length) {// 判斷執(zhí)行完畢的個數(shù)是否等于要執(zhí)行函數(shù)的個數(shù)
      final(results[results.length - 1]);
    }
  })
});

5、異步函數(shù)串行執(zhí)行和并行執(zhí)行結合

假如并行執(zhí)行很多條異步(幾百條)數(shù)據(jù),每個異步數(shù)據(jù)中有很多的(https)請求數(shù)據(jù),勢必造成tcp 連接數(shù)不足,或者堆積了無數(shù)調用棧導致內存溢出。所以并行執(zhí)行不易太多數(shù)據(jù),因此,出現(xiàn)了并行和串行結合的方式。

代碼可以如下書寫:

var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
var running = 0;
var limit = 2;

function async(arg, callback) {
  console.log('參數(shù)為 ' + arg +' , 1秒后返回結果');
  setTimeout(function () { callback(arg * 2); }, 1000);
}

function final(value) {
  console.log('完成: ', value);
}

function launcher() {
  while(running < limit && items.length > 0) {
    var item = items.shift();
    async(item, function(result) {
      results.push(result);
      running--;
      if(items.length > 0) {
        launcher();
      } else if(running == 0) {
        final(results);
      }
    });
    running++;
  }
}

launcher();

6、es6方式

es6天然自帶串行和并行的執(zhí)行方式,例如串行可以用asyncawait(前文已經講解),并行可以用promise.all等等。那么針對串行和并行結合,限制promise all并發(fā)數(shù)量,社區(qū)也有一些方案,例如

tiny-async-pool、es6-promise-pool、p-limit


簡單封裝一個promise all并發(fā)數(shù)限制解決方案函數(shù)

function PromiseLimit(funcArray, limit = 5) { // 并發(fā)執(zhí)行5條數(shù)據(jù)
  let i = 0;
  const result = [];
  const executing = [];
  const queue = function() {
    if (i === funcArray.length) return Promise.all(executing);
    const p = funcArray[i++]();
    result.push(p);
    const e = p.then(() => executing.splice(executing.indexOf(e), 1));
    executing.push(e);
    if (executing.length >= limit) {
      return Promise.race(executing).then(
        () => queue(),
        e => Promise.reject(e)
      );
    }
    return Promise.resolve().then(() => queue());
  };
  return queue().then(() => Promise.all(result));
}

使用:

// 測試代碼
const result = [];
for (let index = 0; index < 10; index++) {
  result.push(function() {
    return new Promise((resolve, reject) => {
      console.log("開始" + index, new Date().toLocaleString());
      setTimeout(() => {
        resolve(index);
        console.log("結束" + index, new Date().toLocaleString());
      }, parseInt(Math.random() * 10000));
    });
  });
}

PromiseLimit(result).then(data => {
  console.log(data);
});

修改測試代碼,新增隨機失敗邏輯

// 修改測試代碼 隨機失敗或者成功
const result = [];
for (let index = 0; index < 10; index++) {
  result.push(function() {
    return new Promise((resolve, reject) => {
      console.log("開始" + index, new Date().toLocaleString());
      setTimeout(() => {
        if (Math.random() > 0.5) {
          resolve(index);
        } else {
          reject(index);
        }
        console.log("結束" + index, new Date().toLocaleString());
      }, parseInt(Math.random() * 1000));
    });
  });
}
PromiseLimit(result).then(
  data => {
    console.log("成功", data);
  },
  data => {
    console.log("失敗", data);
  }
);

7、async 和await 結合promise all

async function PromiseAll(promises,batchSize=10) {
 const result = [];
 while(promises.length > 0) {
   const data = await Promise.all(promises.splice(0,batchSize));
   result.push(...data);
 }
return result;
}

這么寫有2個問題:

  • 1、在調用Promise.all前就已經創(chuàng)建好了promises,實際上promise已經執(zhí)行了
  • 2、你這個實現(xiàn)必須等前面batchSize個promise resolve,才能跑下一批的batchSize個,也就是promise all全部成功才可以。

改進如下:

async function asyncPool(array,poolLimit,iteratorFn) {
  const ret = [];
  const executing = [];
  for (const item of array) {
    const p = Promise.resolve().then(() => iteratorFn(item, array));
    ret.push(p);

    if (poolLimit <= array.length) {
      const e = p.then(() => executing.splice(executing.indexOf(e), 1));
      executing.push(e);
      if (executing.length >= poolLimit) {
        await Promise.race(executing);
      }
    }
  }
  return Promise.all(ret);
}

使用:

const timeout = i => new Promise(resolve => setTimeout(() => resolve(i), i));
return asyncPool( [1000, 5000, 3000, 2000], 2,timeout).then(results => {
    ...
});

到此這篇關于JavaScript異步操作中串行和并行的文章就介紹到這了,更多相關JavaScript異步操作串行和并行內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • JavaScript前端分頁實現(xiàn)示例

    JavaScript前端分頁實現(xiàn)示例

    這篇文章主要為大家介紹了JavaScript前端分頁實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-07-07
  • svgicon組件使用方法示例詳解

    svgicon組件使用方法示例詳解

    這篇文章主要為大家介紹了svgicon組件使用方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • 微信小程序 登陸流程詳細介紹

    微信小程序 登陸流程詳細介紹

    這篇文章主要介紹了微信小程序 登陸流程詳細介紹的相關資料,需要的朋友可以參考下
    2017-01-01
  • 微信小程序 支付簡單實例及注意事項

    微信小程序 支付簡單實例及注意事項

    這篇文章主要介紹了微信小程序 支付簡單實例的相關資料,這里參考官方文檔寫的簡單實例,并提出注意事項,需要的朋友可以參考下
    2017-01-01
  • 微信小程序 滾動到某個位置添加class效果實現(xiàn)代碼

    微信小程序 滾動到某個位置添加class效果實現(xiàn)代碼

    這篇文章主要介紹了微信小程序 滾動到某個位置添加class效果實現(xiàn)代碼的相關資料,需要的朋友可以參考下
    2017-04-04
  • JavaScript遞歸詳述

    JavaScript遞歸詳述

    這篇文章主要介紹了JavaScript遞歸,遞歸就是當一個函數(shù)可以調用自己,那么這個函數(shù)就是遞歸,接下倆我們就來看看下面文章的詳細介紹內容,需要的小伙伴可以參考一下,希望對你有所幫助
    2021-12-12
  • Skypack布局前端基建實現(xiàn)過程詳解

    Skypack布局前端基建實現(xiàn)過程詳解

    這篇文章主要為大家介紹了Skypack布局前端基建過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-07-07
  • Electron 剪貼板實現(xiàn)示例詳解

    Electron 剪貼板實現(xiàn)示例詳解

    這篇文章主要為大家介紹了Electron 剪貼板實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • ECharts圖表使用及異步加載的特性示例詳解

    ECharts圖表使用及異步加載的特性示例詳解

    這篇文章主要為大家介紹了ECharts圖表使用及異步加載的特性詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • js 實現(xiàn)驗證碼輸入框示例詳解

    js 實現(xiàn)驗證碼輸入框示例詳解

    這篇文章主要為大家介紹了js 實現(xiàn)驗證碼輸入框示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-09-09

最新評論