3

I make fetch request in javascript . It is fetching data when I seed console it show me data. but when I try to alert it in then function it displays empty. it show alert promptly with page load. I think it alerting before request response

Here is my javascript code

fetch("https://01b4e41e6262.ngrok.io/api/get_schedule_orders/" + gUser.getData().id).then(res => {
        if (res.ok) {
        alert(res)
        }
    });
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    You should be converting to `res.json` or `res.text` to get the content from response. – HymnZzy Dec 12 '20 at 17:27
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – LeviathanCalumet Dec 12 '20 at 17:42
  • Does this answer your question? [Pure Javascript fetch() method to java Servlet, how do i get and pass data?](https://stackoverflow.com/questions/62029283/pure-javascript-fetch-method-to-java-servlet-how-do-i-get-and-pass-data) – Dan O Dec 12 '20 at 17:47
  • 1
    there are many, many, many Stack Overflow questions about how to access data in the response to `fetch`. which of them have you researched and why did they not solve your particular problem? – Dan O Dec 12 '20 at 17:48

2 Answers2

4

fetch() returns a Promise initially, so res is initially a promise, either resolved or rejected. Then res.json() again returns a promise and not the value directly (You may verify this by doing a console.log(res) in the first then(), there in the prototype you will see json(), which is again Promise based.

That's why we chain promises by doing return res.json() and get our data in the second promise resolve and in case of rejection catch() callback is invoked.

fetch("https://01b4e41e6262.ngrok.io/api/get_schedule_orders/" + gUser.getData().id).then(res => {
    if (res.status>=200 && res.status <300) {
      return res.json()
    }else{
      throw new Error();
    }
}).then(data=>console.log(data))
 .catch(err=>console.log('fetch() failed'))

UPDATE: your API is returning an empty array.

Please check the API params.

API call result

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35
  • @Bilal arshad: The above code handles your error as well and works beautifully in all scenarios. Do rate the accept the answer. Thanks :) God Bless and Happy coding – Imran Rafiq Rather Dec 12 '20 at 17:37
  • I am trying this but not working ```fetch("https://01b4e41e6262.ngrok.io/api/get_schedule_orders/" + gUser.getData().id).then(res => { if (res.status===200) { return res.json(); } }).then(data=> { $scope.schedule_orders = data.data; alert(JSON.stringify(data.json())) });``` –  Dec 12 '20 at 17:42
  • Check whether the API is working fine or not. Try console.log() in your catch() block. Mean while I will see where the problem may be :) – Imran Rafiq Rather Dec 12 '20 at 17:43
  • I checked it, you API is actually returning an empty array. Everything is fine with the code. – Imran Rafiq Rather Dec 12 '20 at 17:48
  • in the preview section i see that ```0: {id: 10, devy_user_id: 129731,…} created_at: null data: "{"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":RPM\"},\"tag\":\"home\"}"}" devy_user_id: 129731 id: 10 schedule_date: "2020-12-12 21:06:00" updated_at: null``` –  Dec 12 '20 at 17:49
  • hmmm. I see. I think I figured it dear brother. Let me debug. – Imran Rafiq Rather Dec 12 '20 at 17:52
  • Replacing this gUser.getData().id by a devy_user_id's value in url returns array with values. See the jsfiddle https://jsfiddle.net/mvjy9e4a/ . You only need to figure our your query parameter correctly and it will work fine i-e , the last part of the url. – Imran Rafiq Rather Dec 12 '20 at 17:56
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/225875/discussion-between-imran-rafiq-rather-and-bilal-arshad). – Imran Rafiq Rather Dec 12 '20 at 17:57
  • Do let me know if it is working fine now :) Do rate and accept in case you learned anything new. For others to also benefit from :) Thank you – Imran Rafiq Rather Dec 12 '20 at 18:05
1

The Fetch API initiates a chain of two Promises.

  • the first promise retrieves the data from the server
  • the second promise resolves the retrieved data (using .text(), .json() etc.)

Example (using async / await syntax):

const getScheduleOrders = async (gUser) => {

  const response = await fetch('https://01b4e41e6262.ngrok.io/api/get_schedule_orders/' + gUser.getData().id);
  const scheduleOrder = await response.text();
  await window.alert(scheduleOrder);
}
Rounin
  • 27,134
  • 9
  • 83
  • 108