动态创建承诺

Creating promises dynamically

我有一个相当简单的问题,我似乎无法解决。我在 google/Whosebug 上也找不到任何内容(也许我只是使用了错误的关键字?)

我有一个值数组,我想为该数组中的每个元素调用某个函数。棘手的是函数 returns 是一个承诺,只有在该承诺得到解决后才应再次调用。

如果我这样做,我就不会在下一个函数调用之前等待 promise 被解决:

let paramerterArr = ['a','b','c','d','e','f']
paramerterArr.forEach((currentParam) => {
    let promise = mySpecialFunction(currentParam)
})

如果我这样做,我将不得不编写大量冗余代码,而且我不能只更改我的数组:

let paramerterArr = ['a','b','c','d','e','f']
mySpecialFunction(paramerterArr[0]).then(()=> {
    return mySpecialFunction(paramerterArr[1])
}).then(()=> {
    return mySpecialFunction(paramerterArr[2])
}).then(()=> {
    return mySpecialFunction(paramerterArr[3])
}).then(()=> {
    return mySpecialFunction(paramerterArr[4])
}).then(()=> {
    return mySpecialFunction(paramerterArr[5])
})

即使我这样做,我也不能只更改数组:

如果我这样做,我将不得不编写大量冗余代码,而且我不能只更改我的数组:

let paramerterArr = ['a','b','c','d','e','f']
let currentPos = 0
mySpecialFunction(currentPos).then(()=> {
    currentPos++
    return mySpecialFunction(currentPos)
}).then(()=> {
    currentPos++
    return mySpecialFunction(currentPos)
}).then(()=> {
    currentPos++
    return mySpecialFunction(currentPos)
}).then(()=> {
    currentPos++
    return mySpecialFunction(currentPos)
}).then(()=> {
    currentPos++
    return mySpecialFunction(currentPos)
})

我只是想不出一个聪明的方法...
也许你们中有人有想法,那就太好了。

如果你想运行你的承诺系列,你可以使用Array.reduce()

parameterArr.reduce(function(promise, item) {
  return promise.then(function(result) {
    return mySpecialFunction(item);
  })
}, Promise.resolve())