Wait for all async functions

Solved!

by kybernaut

JavaScript

// DONT touch: Paralel to GoogleAPI service callback.
function completeTask(task, callback) {
    callback(task);
}

// DONT touch: Paralel to GoogleAPI service.
async function runTask(number) {
    return new Promise((resolve, reject) => {
    		number = number + 10;
        setTimeout(completeTask, 500, number, resolve)
    })
}


// ---

// 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);
  }
};

// The readl handler function.
async function test(numbers) {
		
    let sum = 0;
    console.log('Starting ...');
    
    await numbers.forEach(async (number) => {
        let completed = await runTask(number)
        sum += completed;
        console.log('task ' + number + ' result', completed)
        console.log('current sum', sum)
    });
    
    // Wait for all sync functions to get the final sum.
    console.log('Finished with sum ' + sum);
    return sum;
    
}

//test([1,2,3]);
test([1,2,3]).then((value) => {
  console.log(value);
  // expected output: "36"
});