• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Promise.all(): The Case of the Missing Tuna

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Scene: Catland Central Police Station


Detective Oreo is sipping catnip tea when suddenly—an emergency call comes in:

“THE TUNA IS MISSING FROM THE FRIDGE!”
Oreo slams down his tea. “Not on my watch.”

To solve the case, he must gather three critical clues from different sources:

  1. Pawprint Analysis
  2. Scent Trail Report
  3. Surveillance Footage

Each report takes time, and they are all asynchronous.

Oreo the Async Detective (Enter: Promise.all)


Here’s how it looks in code:


// Simulated async clue fetchers
function getPawprintAnalysis() {
return new Promise(resolve =>
setTimeout(() => resolve("Pawprints match: Garfield"), 1000)
);
}

function getScentTrailReport() {
return new Promise(resolve =>
setTimeout(() => resolve("Scent trail leads to the litter box"), 2000)
);
}

function getSurveillanceFootage() {
return new Promise(resolve =>
setTimeout(() => resolve("Garfield spotted at 2AM near fridge"), 1500)
);
}

Oreo doesn’t want to wait one by one for each clue. So, he does the smart thing:


Promise.all([
getPawprintAnalysis(),
getScentTrailReport(),
getSurveillanceFootage()
]).then(([pawprints, scent, footage]) => {
console.log("Case Clues:");
console.log(pawprints);
console.log(scent);
console.log(footage);
console.log("Oreo concludes: It was Garfield! Case closed.");
});
What Promise.all() Does

  • Runs all clue fetches in parallel
  • Waits for ALL to finish
  • Returns an array of results
  • If any one fails, the whole thing fails (Oreo yells: “Abort!”)
What If One Clue Fails?


Let’s say the surveillance camera was unplugged by a raccoon:


function getSurveillanceFootage() {
return new Promise((_, reject) =>
setTimeout(() => reject("Camera offline! Raccoon sabotage suspected."), 1500)
);
}

Promise.all([
getPawprintAnalysis(),
getScentTrailReport(),
getSurveillanceFootage()
]).then(clues => {
console.log(clues);
}).catch(error => {
console.error("Investigation failed:", error);
console.log("Oreo: ‘Back to square one... but I’ll get that tuna thief.’");
});
Summary Table: Promise.all()

FeatureDescription
PurposeRun multiple promises in parallel
ResultResolves with array of all results
FailureIf one fails, the entire Promise.all() fails
Ideal forWhen all results are required to proceed
Detective Oreo Says:

“If you're solving a crime and need all the clues before pouncing, use Promise.all()—the purr-fect tool for the job.”

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу