0

I'm learning JS and wrote this piece of code.

const functions = [
    prom => {
        console.log(1)
        return prom
    },
    prom => {
        console.log(2)
        return prom
    },
    prom => {
        console.log(3)
        return prom
    }
]

let prom = new Promise((resolve, reject) => {
    resolve()
})

for(functionIndex in functions){
    prom = prom.then(functions[functionIndex])
}

It executes perfectly fine but I'm not really sure it will always execute the functions I pass it in the right order (i.e. the order of the array of functions).

Am I right assuming it will always be the case?

Axel Carré
  • 145
  • 1
  • 8
  • Yes, your functions will execute in the order you expect. If you have `somePromise.then(functionA).then(functionB).then(functionC)`, `functionA` won't be called until/unless `somePromise` is fulfilled; `functionB` won't be called until `functionA` has finished and (optionally) any promise it returns is fulfilled; `functionC` won't be called until `functionB` has finished and (optionally) any promise it returns is fulfilled. ("Fulfilled" here because I'm passing those as the first argument to `then`, which is the fulfillment handler.) – T.J. Crowder Nov 09 '22 at 15:01
  • Side note: You've called the parameter to your functions `prom`, but that's misleading. It will be the fulfillment value of the promise you called `then` on (in your case: `undefined`). The one thing you know for sure about that fulfillment value is that it *won't* be a promise, so `prom` is probably not the name you want. :-) – T.J. Crowder Nov 09 '22 at 15:02
  • Thank you, I knew I about this behavior but the chaining I made inside the loop confused me. Also I called it prom before posting to replace its real name. Thank you. – Axel Carré Nov 09 '22 at 15:07

0 Answers0