简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM