1

Only change the ABC function, how can I get the output in the same order as the function present in the D variable. I have tried using async-await but getting the output as ['123', 'ankit', '345'] because of the timeout event.

const A = (dev) => {
  setTimeout(() => {
    dev('ankit')
  }, 300)
}

const B = (dev) => {
  setTimeout(() => {
    dev('123')
  }, 50)
}

const C = (dev) => {
  setTimeout(() => {
    dev('345')
  }, 500)
}

const D = [A, B, C]

const ABC = (args, dev) => {
  // write your code here
  Promise.all(D.map(async (fun1) => {
    return await fun1(dev)
  }))
}

ABC(D, (result) => {
  console.log('result:', result) // ['ankit', 123, 345]
})
Ankit Kumar Gupta
  • 1,256
  • 1
  • 10
  • 23
  • Can you elaborate on the reason behind your goal? Why use timers in the first place? – Majed Badawi Dec 30 '21 at 15:06
  • @Majed: Assume some API call happening, which will take 300, 500 millisecond. – Ankit Kumar Gupta Dec 30 '21 at 15:07
  • 1
    @JonasWilms - closing with that dup is misunderstanding this question. The OP needs to *promisify* the callback style functions (without editing the original functions). The question is about that (and, incidentally, next about how to invoke promise returning functions in a loop) – danh Dec 30 '21 at 15:43
  • I do not know why they marked the question as duplicate. Anyways I have created a new question. https://stackoverflow.com/questions/70534168/get-the-output-in-the-same-order-as-the-function-available-in-the-array-in-javas – Ankit Kumar Gupta Dec 30 '21 at 16:26
  • @danh I'm always open to suggestions for better duplicates. – Jonas Wilms Dec 30 '21 at 17:16

1 Answers1

0

Since the order of execution depends on the index in the functions array not the execution time, you can simply use a for loop:

const A = dev => new Promise(resolve => 
  setTimeout(() => { dev('ankit'); resolve(); }, 300)
);
const B = dev => new Promise(resolve => 
  setTimeout(() => { dev('123'); resolve(); }, 50)
);
const C = dev => new Promise(resolve =>
  setTimeout(() => { dev('345'); resolve(); }, 500)
);

const ABC = async (args, dev) => {
  for(let i = 0; i < args.length; i++) {
    await args[i](dev);
  }
}

const run = (async () => { 
  await ABC([A, B, C], result => console.log('result:', result));
})();
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48