2

I'm look for a way to chain multiple Promises together similar to Promise.all except I would like each one to wait on the last. I'm sure this has probably been answered already but I don't think I know what to google.

function output(msg) {
 return new Promise((resolve,reject) => {
  console.log(msg);
  resolve();
 });
}

output('1st').then(() => {
 output('2nd').then(() => {
  output('3rd').then(() => {
   console.log('done')
  });
 });
});

// I want to be able to build from an array of length n
const msgs = ['1st','2nd','3rd'];

for(let i = 0; i < msgs.length;i++){
 // Not sure what to do here
 output(msgs[i]).then(() => {
  output(msgs[i+1]);
 });
}
als9xd
  • 834
  • 2
  • 12
  • 23
  • 1
    Related: [Resolve promises one after another (i.e. in sequence)?](https://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence) – CRice Oct 31 '18 at 17:05

2 Answers2

0

You can chain them like so to avoid nesting like hell:

output('a')
    .then(a_out => output('b'))
    .then(b_out => output('c'))
    .then(c_out => console.log('all done'));

and for a sequence of Promise<T>[]:

let loopback = (arr, i=0) => {
    return arr[i].then(() => {
        if (i < arr.length - 1)
            return loopback(arr, i+1);
    });
};

let last = loopback(load);
Rafael
  • 7,605
  • 13
  • 31
  • 46
0

You can use loop like forEach on array and use await inside async function:

function output(msg) {
 return new Promise((resolve,reject) => {
  console.log(msg);
  resolve();
 });
}
const msgs = ['1st','2nd','3rd'];
function ArrPromiseAll(arr) {
  arr.forEach(async function(i) {
    await output(i);
  });
  console.log("Done All.");
}
ArrPromiseAll(msgs);

outputs:

1st
2nd
3rd
Done All.
BladeMight
  • 2,670
  • 2
  • 21
  • 35