Home > Blockchain >  React async call to API not returning when non successful
React async call to API not returning when non successful

Time:05-30

I make a call to an API using the Amplify API:

import { API } from 'aws-amplify'

await API.get('myapi', 'endpoint')
.then(data => {
    // Do something here
})

When my API returns 200 and some data back, then the then body is executed successfully. The problem is, when the endpoint returns 404 (or better non-200 response), it seems like the await API.get .... is not returning and therefore the then body is never executed. I can see in the developer tools and in the Network tab that the call indeed returned a 404 error, it's just in React it never triggers the then body.

This is what the API returns:

return {
    'statusCode': 404,
    'headers': { 
        'Content-Type': 'application/json',
        'Access-Control-Allow-Headers' : 'Content-Type',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET'
    }
}

CodePudding user response:

.then() is triggered when your request is successful and .catch() is triggered when request is rejected. import { API } from 'aws-amplify'

await API.get('myapi', 'endpoint')
 .then(data => {
   // Do something here
 })
 .catch((err) => {
  console.log(err);
});

Plus, I don't think using await along with .then() is a good practice. .then().catch() and async/await are 2 popular ways of handling asynchronous executions.They should not be mixed with each other. Reference link : https://www.geeksforgeeks.org/difference-between-promise-and-async-await-in-node-js/?ref=lbp

  • Related