Reputation: 115
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: '[email protected]',
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>
Upvotes: 0
Views: 525
Reputation: 2576
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: '[email protected]',
password: 'pistol'
}
const registerResult = await axios.post('https://reqres.in/api/register', data);
console.log(registerResult);
} catch (error) {
console.log(error);
}
};
test();
axios.get()
function to execute normally, axios.post()
will be executed.axios.get()
process, an error is thrown
and it will be stopped immediately. then, the error is logged in the catch()
function.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()
Upvotes: 3