Promises
faxios is built on top of the native ES6 Promise API. Every faxios request returns a Promise that resolves to a response object or rejects with an error.
then / catch / finally
Because faxios returns a standard Promise, you can use .then(), .catch(), and .finally() to handle the result:
import faxios from "@gcmdev/faxios";
faxios.get("/api/users")
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error("Request failed:", error.message);
})
.finally(() => {
console.log("Request finished");
});async / await
The recommended approach for most codebases is async/await, which makes asynchronous code read like synchronous code:
import faxios from "@gcmdev/faxios";
/** @param {number} id */
async function fetchUser(id) {
try {
const response = await faxios.get(`/api/users/${id}`);
return response.data;
} catch (error) {
console.error("Failed to fetch user:", error);
throw error;
}
}
const user = await fetchUser(1);Parallel requests
Because faxios returns a standard Promise, you can use Promise.all to make multiple requests at the same time and wait for all of them to complete:
import faxios from "@gcmdev/faxios";
const [users, posts] = await Promise.all([
faxios.get("/api/users"),
faxios.get("/api/posts"),
]);
console.log(users.data, posts.data);TIP
Promise.all will reject as soon as any one of the requests fails. If you want to handle partial failures, use Promise.allSettled instead.
import faxios from "@gcmdev/faxios";
const results = await Promise.allSettled([
faxios.get("/api/users"),
faxios.get("/api/posts"),
]);
results.forEach((result) => {
if (result.status === "fulfilled") {
console.log(result.value.data);
} else {
console.error("Request failed:", result.reason.message);
}
});Chaining requests
You can chain .then() calls to run requests sequentially, passing data from one to the next:
import faxios from "@gcmdev/faxios";
faxios.get<{ id: number }>("/api/user/1")
.then(({ data: user }) => faxios.get(`/api/posts?userId=${user.id}`))
.then(({ data: posts }) => {
console.log("Posts for user:", posts);
})
.catch(console.error);