请求实现异步生成器promisGenerator,按指定顺序返回Promise结果
First, let's fix a critical issue in your promise definitions: the setTimeout calls are invoking resolve immediately instead of waiting for the timeout. You need to pass a callback function to setTimeout instead of calling resolve directly. That's why your original code would resolve all promises right away, leading to output in array order instead of the expected sequence.
Here's the corrected promise list:
const promisList = [ new Promise(resolve => setTimeout(() => resolve(15), 200)), new Promise(resolve => setTimeout(() => resolve(17), 600)), new Promise(resolve => setTimeout(() => resolve(42), 500)) ];
Now, to create an async generator that yields results in the order 17, 42, 15 (which matches the reverse of when each promise resolves), we can follow these steps:
- Wrap each promise to capture its resolution timestamp
- Wait for all promises to resolve
- Sort the resolved results by their resolution time (latest first)
- Yield each value in the sorted order
Here's the implementation of promisGenerator:
async function* promisGenerator(arrPromise) { // Wrap each promise to track when it resolves const wrapped = arrPromise.map(async (p) => { const value = await p; return { value, resolvedAt: Date.now() }; }); // Wait for all promises to complete const results = await Promise.all(wrapped); // Sort results by resolution time (newest first) results.sort((a, b) => b.resolvedAt - a.resolvedAt); // Yield each value in the sorted order for (const result of results) { yield result.value; } }
When you run this corrected code, the output will be 17, then 42, then 15 as expected. The generator waits for all promises to resolve, sorts them by when they finished (latest first), then yields each value in that sequence.
If instead you wanted to yield values in the specific hardcoded order 17, 42, 15 regardless of resolution time, you could collect all resolved values first, then reorder them explicitly:
async function* promisGenerator(arrPromise) { const values = await Promise.all(arrPromise); // Define the desired order of values const desiredOrder = [17, 42, 15]; // Yield each value in the desired sequence for (const val of desiredOrder) { yield val; } }
This approach is simpler but only works if you know the exact values you want to yield in advance.
内容的提问来源于stack exchange,提问作者Edgar

