0

Given

const list = [1,2,3,4,5,6,7];
let results = [];

and a function

powerNumPlusOne = async(num) : Promise<any> => {
     return powerNum*powerNum + 1;
} 

how to make sure this code work

list.forEach(async function(i){
   results.push( await this.powerNumPlusOne(i));
})

and the results should be [2,5,10,17,26,37,50] in order?

Jerry
  • 329
  • 1
  • 4
  • 13
  • Your function does nothing asynchronous. Just make it synchronous, don't return a promise, and you won't have any problems. (Btw this is also the reason why your example already does output the expected result) – Bergi Nov 22 '19 at 01:28
  • https://caolan.github.io/async/v3/index.html `const _async = require('async'); let results = []; let tasks = []; list.forEach((i) => { tasks.push((callback) => { this.powerNumPlusOne(i).then( (res) => { results.push(res); callback(null, res); } ); }) }) _async.series(tasks, (err, res) => { console.log(res); })` – Jerry Nov 22 '19 at 04:03
  • No, if you want to work with promises, don't use the `async.js` library for callback-style. – Bergi Nov 22 '19 at 08:54
  • yes. but it did work. I wrote codes in typescript. Thanks! – Jerry Nov 24 '19 at 14:32

1 Answers1

-1

You could use Promise.all(). It accepts an number of actions and returns them in exactly the same order when all complete.

const list = [1,2,3,4,5,6,7];
let actions = list.map(powerNumPlusOne);
let results = await Promise.all(actions);
enter code here
Ciamas
  • 41
  • 2
  • 7