0

我正在尝试在 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()
  })
}

谢谢你的帮助。

4

2 回答 2

6

你不能使用forEach它(至少,不是不访问外部变量) - 如果你想使用数组方法,请使用reduce,并每次将当前 Promise 作为累加器传递:

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

或者,如果您想让代码更易于阅读,请awaitfor循环中使用:

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

于 2019-02-28T05:58:42.027 回答
1

您需要读取从承诺返回的数据

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

于 2019-02-28T06:00:59.467 回答