Search code examples
javascriptes6-promise

How to get the index of the Promise returned by Promise.any from an array of Promises?


I'm trying to implement a queue of promises that fetch images. So, I create an array of 3 promises and get the first fetched image using Promise.any(). But when I receive the first image, I want to replace the used promise with a new one. Example:

const images = [
    fetch("some/image"),
    fetch("another/image"),
    fetch("another/image"),
];

Promise.any(images).then(img => {
    images[n] = fetch("another/image") // if only I knew "n"
    return img
}).then(/*whatever*/)

I've tried finding the index by comparing each promise of the array to the one returned by Promise.any, but that didn't work since it returns a new promise.

So, how do I know the index of the promise who's value was returned by Promise.any's promise?


Solution

  • You can add index for each image promise before passing them to Promise.any (add .then chain)

    const images = [
        Promise.resolve("some/image1"),
        Promise.resolve("some/image2"),
        Promise.resolve("some/image3"),
    ];
    
    Promise.any(images.map((p, i) => p.then(v => [v, i]))).then(([img, index]) => {
        console.log('image', img)
        console.log('index', index)
    })