LearnFrenzy
Sign in Take a free test

Promises · Promises Coding Problems · Question 7

Download from the fastest working mirror with Promise.any in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Request a file from several mirrors at once and use the first one that succeeds, ignoring failed mirrors; report an error only if every mirror fails.

Solution
main.js
const mirror = (name, ms, ok) =>
  new Promise((resolve, reject) => setTimeout(() => (ok ? resolve(`${name} (${ms} ms)`) : reject(new Error(`${name} down`))), ms));

const download = (mirrors) =>
  Promise.any(mirrors.map(([name, ms, ok]) => mirror(name, ms, ok)))
    .then((from) => `downloaded from ${from}`)
    .catch((e) => `all mirrors failed: ${e.errors.map((x) => x.message).join(", ")}`);

download([["mumbai", 5, false], ["singapore", 25, true], ["frankfurt", 15, true]]).then(console.log);
download([["a", 5, false], ["b", 8, false]]).then(console.log);

Output Verified by running it on Node.js

all mirrors failed: a down, b down
downloaded from frankfurt (15 ms)

any ignores rejections (Mumbai fails at 5 ms) and fulfils with the first success – Frankfurt at 15 ms. When every mirror fails, it rejects with an AggregateError listing all reasons; the second download settles first because its mirrors fail at 5 and 8 ms.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links