提问者:小点点

如何在forEach[副本]中逐个运行Promise


我正试图在Foreach内部一个接一个地运行一个承诺。

对不起,我知道这可能是一个简单的问题,但我发现很难找到一个答案,如何解决这个问题。

我希望console.log显示如下

test
a
test
b
test
c

但是,它是这样显示的

test
test
test
a
b
c

这是我的代码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()
  })
}

谢谢你的帮助。


共2个答案

匿名用户

您不能为此使用(至少,不是在不访问外部变量的情况下)--如果您想使用数组方法,则使用,并每次传递当前承诺作为累加器:

null

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()
  })
}

匿名用户

您需要读取从promise返回的数据

null

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')
  })
}