AlexZeDim
AlexZeDim

Reputation: 4352

Access current iteration (index) during for await of loop javascript

There is a question about for await ... of loop.

I have the following code:

    for await (let V of reagentItems.map(objectElement => getPricing(objectElement))) {
       console.log(objectElement) //I'd like to have access to the current iteration.
       //or
       console.log(reagentItems[i]) //current fulfilled element from reagent.map
    }

So the problem is that this array (from .map) of functions (V as a single response of getPricing) doesn't return the objectElement itself but I need to have access to this objectElement inside for await ... of loop.

Does it possible somehow or not? And if it doesn't, using of Promise.all handles this problem somehow? Or I should modify the original getPricing and return current objectElement with other results?

Upvotes: 4

Views: 11473

Answers (2)

Bergi
Bergi

Reputation: 665276

You should not be using for await here at all - that is meant for asynchronous generators. Instead, do

for (const object_element of reagent_items) {
    const V = await getPricing(object_element);
    console.log(object_element, V)
    …
}

With Promise.all, the code would look like this:

Promise.all(reagent_items.map(object_element =>
    getPricing(object_element).then(V => {
        console.log(object_element, V);
        …
    })
)).then(…)

// or:

await Promise.all(reagent_items.map(async object_element => {
    const V = await getPricing(object_element)
    console.log(object_element, V);
    …
}));

Upvotes: 0

fjc
fjc

Reputation: 5825

From what I can understand from your question and your comments, you want to be able to access both object_element and the result of getPricing(object_element) within the for loop.

Your problem right now is that as a result of map, you only have the result of getPricing, but not the original object_element. As a solution, simply return both from map in an object:

// just a random getPricing function
function getPricing(objectElement) {
    return {
        item_id: objectElement.id,
        price: Math.random()
    };
}

const reagent_items = [
    {
        id: 'a'
    },
    {
        id: 'b'
    }
];

for (let V of reagent_items.map(object_element => ({object_element, pricing: getPricing(object_element)}))) {
    console.log(`object_element: ${JSON.stringify(V.object_element)}, pricing: ${JSON.stringify(V.pricing)}`);
}

Upvotes: 1

Related Questions