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

Time:08-04

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?

CodePudding user response:

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)
})

CodePudding user response:

Consider using promise-limit package for this purpose. It allows you to solve your problem in a more robust way:

var promiseLimit = require('promise-limit')
 
var limit = promiseLimit(2) // max count of simultaneous requests
 
var allImages = ['a', 'b', 'c', 'd', 'e']
 
Promise.all(allImages.map((name) => {
  return limit(() => fetch(name).then(imageLoadedCallback))
}))
  • Related