1

I am making a POST REST API call and I guess I am missing something in the await. It's probably because I am new to the Javascript world. Below is my code :

var values = await sendNetworkRequest("",serverResponse);
logInfo(values);

And function sendNeworkRequest is the one which actually makes a API call :

async function sendNetworkRequest(text,cb) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST",________);
    xhr.setRequestHeader(_____);
    var jsonData = JSON.stringify(________);
    xhr.send(jsonData);
    xhr.onload = function () {
      var res = JSON.parse(xhr.responseText);
      cb(res);
    }
}

function serverResponse(data) {
    console.log(data['ProviderIds']);  // all good here
    return data['ProviderIds']; 
}

I successfully get the data in the variable 'data'. However, it is late by a few mili-seconds that the variable 'values' is not set. It remains undefined. I also tried only to find out the same behaviour.

sendNetworkRequest("",serverResponse).then(values => {
   // values remains undefined
});

Can anybody help me to get return value in the variable 'values' ? Thanks in advance.

EDIT :

Following doesn't work too :

xhr.onload = await function () {
     var res = JSON.parse(xhr.responseText);
        //   cb(res);  
     return res['ProviderIds'];
}
Sukhi
  • 13,261
  • 7
  • 36
  • 53
  • 4
    you've wrapped the XHR request in an async function...but you still aren't actually waiting for the onload event to occur. The serverResponse callback (which btw is a perfectly reasonable approach to getting at your data) will be executing after your LogInfo command. And also, even if none of that were true or relevant, `sendNetworkRequest` doesn't actually return anything. So `values` will always be null no matter what. – ADyson May 12 '20 at 14:20
  • `sendNetworkRequest` doesn't return anything. – Titus May 12 '20 at 14:21
  • 3
    For an example of how to wrap `XMLHttpRequest` correctly, see [my answer here](https://stackoverflow.com/a/50952071/157247). But you don't have to do that; you can use [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) instead (also described and shown in that answer). Just beware of [the `fetch` footgun](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html). – T.J. Crowder May 12 '20 at 14:22
  • Anyway instead of using the antiquated XmlHttpRequest, if you're wanting to make an AJAX request, I would suggest using the more modern fetch() API which supports async/await syntax directly without the need for wrappers or callbacks. This might be a useful article to help with that: https://medium.com/better-programming/from-xhr-to-fetch-with-async-await-on-the-finish-line-b021de1d226b – ADyson May 12 '20 at 14:23
  • Re the "Following doesn't work too :" edit ...that code is total gibberish for a couple of reasons, but it's not worth going into it. Follow the advice given above by me and others, and get up-to-date, and make your life easier, by using fetch() instead of XHR. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API . Or if you really must use XHR for some reason (e.g IE11 support), then see TJ Crowder's link above already about how to correctly wrap it in asynchronous code. You don't need to solve this yourself, it's already been done many times before. – ADyson May 12 '20 at 14:26
  • 1
    Thanks @ADyson and @T.J.Crowder. The `await fetch()` works and I improved my code as well. Thanks a bunch for a quick help. – Sukhi May 12 '20 at 14:48

0 Answers0