Skip to content Skip to sidebar Skip to footer

How To Await A Json Return Value (the Return Takes At Least 30 Seconds) Before Logging It? Javascript/react/express

This is a follow up to these threads: How to set state of a react component with a specific item from a returned json object? How to return json data to a react state? I am using w

Solution 1:

First block of code seems working, may be you want to attach .catch to it as error handler.

axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response =>console.log(response.data))
  .catch(function(error) {
    console.log(error);
  });
<scriptsrc="https://unpkg.com/axios/dist/axios.min.js"></script>

In second part I think you are doing await wrong. You are awaiting on a function which never gets called. Await is supposed to be listening on something that gets called in below instance a promise returned by axios

const samplePayload = {
  "userId": 100,
  "id": 100,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
};


// Using GET here for demo but you can swap it with POSTconst onSuccess = async payment => {
  returnawait axios.get(
    "https://jsonplaceholder.typicode.com/posts", samplePayload
  ).then(res => {
    console.log(res.data);
  });
}

console.log(onSuccess());
<scriptsrc="https://unpkg.com/axios/dist/axios.min.js"></script>

I hope that clarifies.

Solution 2:

Your second is wrong, you are never getting the response

const onSuccess = async payment => {
  const res = await axios.post(
    "http://ec2-54-67-28-69.us-west-1.compute.amazonaws.com:3000/users",
    {
    value: "value",
    fileName: "fileName",
    hash: "hash"
    }
  );
  console.log(res.data);
  return res.data
}

Also, as Rikin said, your first code seems ok. Try adding the .catch

Post a Comment for "How To Await A Json Return Value (the Return Takes At Least 30 Seconds) Before Logging It? Javascript/react/express"