Edgar
Edgar

Reputation: 6856

Asynchronous generator and array promise

This my code

async function* promisGenerator(arrPromise) {}  //???

const promisList = [
  new Promise(resolve => setTimeout(resolve(15), 200)),
  new Promise(resolve => setTimeout(resolve(17), 600)),
  new Promise(resolve => setTimeout(resolve(42), 500))
];

(async () => {
  const asyncGenerator = promisGenerator(promisList);
  for await (let value of asyncGenerator) {
    console.log(value); // 17, 42, 15,
  }
})();

i have array promise. I have to write an asynchronous generator promisGenerator,which we will return the value in descending order 17, 42, 15.please help write a generator promisGenerator.

Upvotes: 0

Views: 849

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

Assuming that you want the array of Promises to resolve in the order of the second parameter passed to setTimeout, you need to promisify them properly. (Don't call resolve immediately - rather, just pass resolve to setTimeout.) Then, chain a .then onto each Promise which pushes the resolve value to an array. Await a Promise.all on the array of Promises, and then you can reverse the array of values and yield each of them:

async function* promisGenerator(arrPromise) {
  const resolvedValues = [];
  arrPromise.forEach(prom => prom.then(value => resolvedValues.push(value)));
  await Promise.all(arrPromise);
  resolvedValues.reverse();
  for (const value of resolvedValues) {
    yield value;
  }
}

const promisList = [
  new Promise(resolve => setTimeout(resolve, 200, 15)),
  new Promise(resolve => setTimeout(resolve, 600, 17)),
  new Promise(resolve => setTimeout(resolve, 500, 42))
];

(async() => {
  const asyncGenerator = promisGenerator(promisList);
  for await (let value of asyncGenerator) {
    console.log(value); // 17, 42, 15,
  }
})();

Upvotes: 1

Related Questions