0

I want make a Get Request with axios get method and chain a post Request if the Promise is successful

Endpoint is a API the Promise who should return the Promise from the Get Request returns the GET Request Promise

considering this answer calling a async function inside then this should be possibly

why does the post request gets not trough ?

axios.get('https://reqres.in/api/users/')
.then(() => {
    data = {
        email: 'eve.holt@reqres.in',
        password: 'pistol'
    }
    return data
}).then((data) => {
    const postRequest = axios.post('https://reqres.in/api/register', data);
    return postRequest
}).then((response) => {
    console.log(response)
}).catch((response) => {
    console.log(response)
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Http Requests & JavaScript</title>
        <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"> 
        </script>
    </head>

    <body>
    </body>
</html> 
myeongkil kim
  • 2,465
  • 4
  • 16
  • 22
seeman
  • 105
  • 1
  • 13

1 Answers1

3

If you use async, how about using await? I have now translated your code using await.

// test.js
const axios = require('axios');

const test = async () => {
    try {
        await axios.get('https://reqres.in/api/users/');
        const data = {
            email: 'eve.holt@reqres.in',
            password: 'pistol'
        }
        const registerResult = await axios.post('https://reqres.in/api/register', data);
        console.log(registerResult);
    } catch (error) {
        console.log(error);
    }
};

test();
  • After waiting for the axios.get() function to execute normally, axios.post() will be executed.
  • If an error is returned from axios.get() process, an error is thrown and it will be stopped immediately. then, the error is logged in the catch() function.
  • (Of course) Also, even if axios.get() function works normally, if a problem occurs in axios.post() function, it will catch() error.

[P.S] Additionally if you want to get the result by axios.get(), you can use it after assigning the result to a variable like const users = await axios.get()

myeongkil kim
  • 2,465
  • 4
  • 16
  • 22
  • `async/await` looks so clean compared to the `.then().then()` Promise style, or even worse, a good old callback hell. Upvoted, that's the way to go – Jeremy Thille Jan 24 '21 at 16:04
  • I just realized that my code also works, but your solution looks way cleaner ! – seeman Jan 24 '21 at 18:10