-1

I am trying to run a promise one by one inside forEach.

Sorry, I know this might be a simple question, however I find it difficult to find an answer on how to solve this.

I expect the console.log will show like this

test
a
test
b
test
c

However, it shows like this

test
test
test
a
b
c

This is my code https://jsfiddle.net/brianivander/b6csvrn9/1/

var array1 = ['a', 'b', 'c'];
array1.forEach(function(element) {
  promise().then(() => {
    console.log(element);
  })
});

function promise() {
  return new Promise((resolve, reject) => {
    console.log('test');
    resolve()
  })
}

Thanks for your help.

Brian Ivander T. P.
  • 415
  • 2
  • 8
  • 22

2 Answers2

6

You can't use forEach for that (at least, not without accessing an external variable) - if you want to use an array method, use reduce instead, and pass along the current Promise as the accumulator each time:

var array1 = ['a', 'b', 'c'];
array1.reduce((a, str) => (
  a.then(promise)
    .then(() => {
      console.log(str);
    })
), Promise.resolve());

function promise() {
  return new Promise((resolve, reject) => {
    console.log('test');
    resolve()
  })
}

Or, if you wanted to make the code easier to read, use await inside a for loop:

var array1 = ['a', 'b', 'c'];
(async () => {
  for (const str of array1) {
    await promise();
    console.log(str);
  }
})();


function promise() {
  return new Promise((resolve, reject) => {
    console.log('test');
    resolve()
  })
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

you need to read the data which is returned from the promise

var array1 = ['a', 'b', 'c'];
array1.forEach(function(element) {
  promise().then((result) =>  {
    
    console.log(result);
    console.log(element);
  })
});

function promise() {
  return new Promise((resolve, reject) => {
    resolve('test')
  })
}
Kaushik
  • 2,072
  • 1
  • 23
  • 31