Forivin
Forivin

Reputation: 15518

Creating promises dynamically

I have a rather simple problem that I don't seem to be able to solve. I also couldn't find anything on google/stackoverflow (maybe I'm just using the wrong keywords?)

I have an array of values and I would like to call a certain function for every single element in that array. The tricky thing is that the function returns a promise and should only be called again once that promise has been resolved.

If I would do it like this, I wouldn't be waiting for the promise to be resolved before the next function call:

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

If I would do it like this I would have to write a lot of redundant code and I can't just change my array:

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

And even if I would do it like this I couldn't just change the array:

If I would do it like this I would have to write a lot of redundant code and I can't just change my array:

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

I just can't think of a smart way to do it...
Maybe someone of you has an idea, that would be great.

Upvotes: 1

Views: 674

Answers (1)

hackerrdave
hackerrdave

Reputation: 6706

If you want to run your promises in series you can use Array.reduce()

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

Upvotes: 2

Related Questions