Await Foreach example

by kybernaut

JavaScript

// Await for each
// https://itnext.io/why-async-await-in-a-foreach-is-not-working-5f13118f90d

Array.prototype.forEach = async function forEach(callback, thisArg) {
  if (typeof callback !== "function") {
    throw new TypeError(callback + " is not a function");
  }
  var array = this;
  thisArg = thisArg || this;
  for (var i = 0, l = array.length; i !== l; ++i) {
    await callback.call(thisArg, array[i], i, array);
  }
};

const AIFoodRecognition = (food) => {
  const dictionary = {
    orange: "fruit",
    salami: "meat",
    salmon: "fish",
    kale: "vegetable",
    banana: "fruit",
  };

  return new Promise((r) =>
    setTimeout(() => {
      return r(`${food} is a ${dictionary[food]}`);
    }, 500)
  );
};

const foodArray = ["orange", "salami", "salmon", "kale", "banana"];

const run = async () => {
  console.log("Start")
  
  await foodArray.forEach(async (food) => {
    const output = await AIFoodRecognition(food);
    console.log(output);
  });
  
  console.log("End")
};


run()