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

JavaScript異步操作中串行和并行

 更新時(shí)間: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方案。假如多個(gè)異步函數(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ù)是一個(gè)一個(gè)執(zhí)行的,上一個(gè)執(zhí)行結(jié)束再執(zhí)行下一個(gè),類似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í)行完畢的個(gè)數(shù)是否等于要執(zhí)行函數(shù)的個(gè)數(shù)
      final(results[results.length - 1]);
    }
  })
});

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

假如并行執(zhí)行很多條異步(幾百條)數(shù)據(jù),每個(gè)異步數(shù)據(jù)中有很多的(https)請求數(shù)據(jù),勢必造成tcp 連接數(shù)不足,或者堆積了無數(shù)調(diào)用棧導(dǎ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


簡單封裝一個(gè)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);
});

修改測試代碼,新增隨機(jī)失敗邏輯

// 修改測試代碼 隨機(jī)失敗或者成功
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個(gè)問題:

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

改進(jìn)如下:

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 => {
    ...
});

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

相關(guān)文章

最新評論

双江| 龙川县| 银川市| 张北县| 政和县| 民勤县| 凤阳县| 平舆县| 东乌| 柘荣县| 九龙坡区| 铜鼓县| 榕江县| 平泉县| 延寿县| 闵行区| 沈阳市| 河津市| 治多县| 新和县| 凤凰县| 普格县| 卢氏县| 奈曼旗| 彝良县| 和顺县| 延安市| 黎平县| 通化市| 涪陵区| 巴林左旗| 民权县| 灯塔市| 富平县| 锡林浩特市| 凤冈县| 沽源县| 会宁县| 黎川县| 江北区| 晋江市|