Lỗi Hay Gặp Khi Sài Vòng Lặp Và Xử Lý Bất Đồng Bộ

Bạn nghĩ sao khi đoạn mã ở dưới thực thi, ở console của trình duyệt sẽ in ra kết quả gì.

import _ from 'lodash';
import 'babel-polyfill';

let counter = 0;
(async () => {

  _.forEach([1, 2, 3, 4, 5], async item => {
    console.log("counter", counter);
    if (counter < 2) {
      counter++;
    } else {
      counter = 0;
    }
  });
  console.log("async called");
})();

Chắc ai cũng biết được kết quả là gì rồi chứ nhỉ

0 1 2 0 1

Nếu mình thấy đổi đoạn mã phía trên là trong forEach có xử lý 1 async function, thì kết quả sẽ như thế nào:

import _ from 'lodash';
import 'babel-polyfill';

function awaitFunction(value) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(value);
    }, 1000);
  });
}

let counter = 0;
(async () => {

  _.forEach([1, 2, 3, 4, 5], async item => {
    console.log("counter", counter);
    if (counter < 2) {
      counter++;
    } else {
      await awaitFunction(item); // Đoạn mới được thêm
      counter = 0;
    }
  });
  console.log("async called");
})();

Và giờ kết quả không còn giống như trên nữa nha các bạn. Nó sẽ in ra màn hình là

0 1 2 2 2

Cách fix lỗi trên là mình chuyển qua sài vòng lặp for… of

import _ from 'lodash';
import 'babel-polyfill';

function awaitFunction(value) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(value);
    }, 1000);
  });
}

let counter = 0;
(async () => {

  for(let item of [1, 2, 3, 4, 5]) {
    console.log("counter", counter);
    if (counter < 2) {
      counter++;
    } else {
      await awaitFunction(item);
      counter = 0;
    }
  });
  console.log("async called");
})();

 

Rate this post

You May Also Like

About the Author: truongluu

Leave a Reply

Your email address will not be published. Required fields are marked *