最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript異步操作中串行和并行

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

1、前言

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

2、es5方式

在es6出來之前,社區(qū)nodejs中針對回調(diào)地獄,已經(jīng)有了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秒后返回結(jié)果');
  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í)行結(jié)束再執(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秒后返回結(jié)果');
  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í)行結(jié)合

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

代碼可以如下書寫:

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秒后返回結(jié)果');
  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(前文已經(jīng)講解),并行可以用promise.all等等。那么針對串行和并行結(jié)合,限制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("結(jié)束" + 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("結(jié)束" + index, new Date().toLocaleString());
      }, parseInt(Math.random() * 1000));
    });
  });
}
PromiseLimit(result).then(
  data => {
    console.log("成功", data);
  },
  data => {
    console.log("失敗", data);
  }
);

7、async 和await 結(jié)合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、在調(diào)用Promise.all前就已經(jīng)創(chuàng)建好了promises,實際上promise已經(jīng)執(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異步操作串行和并行內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

汉阴县| 兴业县| 北流市| 青冈县| 翁牛特旗| 扶风县| 左权县| 鲜城| 基隆市| 奉化市| 通州区| 荆门市| 江城| 靖宇县| 望谟县| 临漳县| 贵港市| 榆树市| 博爱县| 马边| 师宗县| 汝城县| 洛川县| 桐柏县| 吉木萨尔县| 阿拉善左旗| 莱西市| 彰化县| 二连浩特市| 南城县| 天门市| 上蔡县| 丹棱县| 洪泽县| 新平| 叙永县| 鹤峰县| 中牟县| 长丰县| 贵州省| 兴义市|