我正试图在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()
})
}
谢谢你的帮助。
您不能为此使用
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')
})
}