Skip to content

Instantly share code, notes, and snippets.

@mikaelhadler
Created August 20, 2024 02:02
Show Gist options
  • Save mikaelhadler/593dd0038f1e46cf48c7d9c91dc16ff9 to your computer and use it in GitHub Desktop.
Save mikaelhadler/593dd0038f1e46cf48c7d9c91dc16ff9 to your computer and use it in GitHub Desktop.
const firstRequest = () =>
fetch("https://api.github.com/users/mikaelhadler").then((res) => {
console.log("First request completed");
if (!res.ok) {
return res.json().then((errorData) => {
throw new Error(`Failed at firstRequest: ${errorData.message}`);
});
}
return res.json();
});
const secondRequest = () =>
fetch("https://api.github.com/users/x").then((res) => {
console.log("Second request completed");
if (!res.ok) {
return res.json().then((errorData) => {
throw new Error(`Failed at secondRequest: ${errorData.message}`);
});
}
return res.json();
});
const thirdRequest = () =>
fetch("https://api.github.com/users/xx").then((res) => {
console.log("Third request completed");
if (!res.ok) {
return res.json().then((errorData) => {
throw new Error(`Failed at thirdRequest: ${errorData.message}`);
});
}
return res.json();
});
const allRequests = [firstRequest, secondRequest, thirdRequest];
const executeRequests = () =>
allRequests.reduce(
(promiseChain, currentRequest) =>
promiseChain.then((results) =>
currentRequest(results[results.length - 1])
.then((result) => [...results, result])
.catch((error) => {
throw error;
})
),
Promise.resolve([])
);
executeRequests()
.then((allResults) => {
console.log("All results:", allResults);
})
.catch((error) => {
console.error("Execution stopped due to error:", error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment