The `then()` Function in Axios

Mar 30, 2020

Axios requests are actually promises. Than means you can use them with promise chaining and async/await.

const axios = require('axios');

const req = axios.get('https://httpbin.org/get?hello=world');

req instanceof Promise; // true

const res = await req;
res.data.args; // { hello: 'world' }
return req.then(res => {
  res.data.args; // { hello: 'world' }
});

Handling Errors

Axios fulfills the request promise when the server responds with an HTTP success code, or rejects the request promise when the server responds with an HTTP error. If an error occurs, you can handle the error with .then() or .catch().

const axios = require('axios');

const err = await axios.get('https://httpbin.org/status/404').
  then(() => null, err => err);

err.response.status; // 404
err.response.statusText; // 'NOT FOUND'

Axios Requests Execute Immediately

You do not need to call .then() or .catch() to execute an Axios request. Axios executes the request immediately on its own. So even if you don't call then(), your server will still get the request.

const axios = require('axios');
const express = require('express');

// Create a dummy Express server that stores all inbound
// requests
const app = express();
const requests = [];
app.get('*', function(req, res) {
  requests.push(req);
  res.json({ ok: 1 });
});
const server = await app.listen(3000);

// Send a request without calling `then()`.
axios.get('http://localhost:3000');

// The server got the request.
await new Promise(resolve => setTimeout(resolve, 100));
requests.length; // 1

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!