ARMATAV
ARMATAV

Reputation: 634

Chaining this promise

What's the proper way to chain something when you need to append the results to an array that is sitting at the top level of a function's scope?

function run() {
    let array = []

    let input = 'object'

    promiseA(input)
    .then((result) => {
        array.push(result)
    })

    promiseB(input)
    .then((result) => {
        array.push(result)
    })

    console.log(array.join(' '))
}

Order doesn't matter for my application, I can parallelize it if that's considered best practices. It's literally just checking for a condition, there's no async calls to get results from an API or anything like that.

Upvotes: 0

Views: 65

Answers (4)

Ele
Ele

Reputation: 33736

An alternative is using async function:

This approach executes the promises one by one, that way you will be able to handle the result with the desired execution order.

function promiseA(input) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve(input);
    }, 1000);
  });
}

function promiseB(input) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve(input);
    }, 500);
  });
}

async function run() {
  let array = [];
  
  let input = 'Ele';
  array.push(await promiseA(input));

  input = "from SO";
  array.push(await promiseB(input));

  console.log(array.join(' '))
}

console.log('Wait for 1.5sec...')
run()

Upvotes: 1

Randy Casburn
Randy Casburn

Reputation: 14185

Answering the Question Asked

This is the correct way to sequence or chain Promises:

one(arr).then(two).then(log, fail);

This directly answers the question without offering other possible solutions.

Please note there are no side effects. The "scope" issue mentioned in the comments is absolutely avoided.

The sample snippet implements this:

let arr = [];

function one(arr) {
  return new Promise((res, rej) => {
    arr.push('one');
    res(arr);
  });
}
function two(arr) {
  return new Promise((res, rej) => {
    arr.push('two');
    res(arr);
  });
}

function log(arr){
  console.log(arr);
}

function fail(reason){
  console.log(reason);
}



one(arr).then(two).then(log, fail);

Upvotes: 0

Ricardo
Ricardo

Reputation: 2497

your function will look like this

function run () {
 return Promise.all([promiseA(), promiseB()]).then(([resultA, resultB])=>{ }) 
}

Upvotes: 2

iCode
iCode

Reputation: 1346

You should use Promise.all to wait for promise A and promise B to complete. Promise.all will receive an array of results (from each Promise) that you can then use.

You might have something like:

var promiseA =       doSomethingThatReturnsPromise(input);
var promiseB = doSomethingThatReturnsPromise(anotherInput);

Promise.all([promiseA, promiseB]).then(function(resultsArray) { // do something });

Upvotes: 2

Related Questions