0

I have two functions,

function getRequest(url, api_key, callback) {
    $.ajax({
        url: url,
        contentType: 'application/json',
        type: 'get',
        beforeSend: function(xhr){
            xhr.setRequestHeader('Authorization', 'Bearer ' + api_key);
        },
        success: function(response) {
            callback(response);
        },
        error: function(error) {
            console.log(error);
            document.getElementById("droplets").textContent = error;
        }
    });
}

function getDroplets(url, api_key) {
    var request = getRequest(url, api_key, function(response) {
        var droplets = response.droplets;
        var numDroplets = droplets.length;
        return {
            droplets: droplets,
            numDroplets: numDroplets
        };
    });
    alert(request);
}

I want to have another function, let's call it listDroplets, that will call getDroplets() and manipulate the data returned from it. I'm not sure how to do this because getDroplets has an asynchronous call within it.

EDIT: I have tried the following, but it still doesn't work.

async function listDroplets() {
    await getDroplets(api_url, api_key);
    alert(request.numDroplets);
}
Jordan Baron
  • 3,752
  • 4
  • 15
  • 26
  • But also : https://stackoverflow.com/questions/34210812/how-to-use-async-await-function-object-in-javascript?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – mplungjan May 15 '18 at 12:48
  • 1
    getRequest should return `$.ajax(...` drop the success and error. In getDroplets you can do `getrequest(...).then(result=>{return alteredResult}).then(finalResult=>...).catch(error=>handle your error)` currently getting a request (called getRequest) is implementing something that getDroplets should implement (when there is an error) – HMR May 15 '18 at 12:50
  • @mplungjan see my updated post – Jordan Baron May 15 '18 at 13:00
  • @HMR how would I return the result if success is what's called when the Ajax request is successful? – Jordan Baron May 15 '18 at 13:05
  • reopened, but still a dupe of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – mplungjan May 15 '18 at 13:07
  • [jQuery.ajax](http://api.jquery.com/jquery.ajax/) returns a promise like object, you can try to have a look at promises, change your code and if that doesn't work edit the question again for us to have a look at. – HMR May 15 '18 at 13:19

1 Answers1

2

Here are how your functions could return promise like objects that you can use in an async await function:

function getRequest(url, api_key, callback) {
  //to escape terrible jQuery Deferred and comfortably continue in Promise land
  // you can do
  // const deferred = $.ajax(...); return Promise.resolve(deferred)
  return $.ajax({//return promise like object
    url: url,
    contentType: 'application/json',
    type: 'get',
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + api_key);
    }
  });
}

function getDroplets(url, api_key) {
  return getRequest(url, api_key)//return promise like object
  .then(function (response) {//
    var droplets = response.droplets;
    var numDroplets = droplets.length;
    return {
      droplets: droplets,
      numDroplets: numDroplets
    };
  })
  .catch(function (error) {//implement error if something goes wrong
    console.log(error);
    document.getElementById("droplets").textContent = error;
  });
}


async function listDroplets() {
  //depending on how old your jQuery is you may want to do this:
  // await Promise.resolve(getDroplets(api_url, api_key));
  const request = await getDroplets(api_url, api_key);
  //note that if something goes wrong then request is undefined (depending on jQuery version)
  alert(request.numDroplets);
}
HMR
  • 37,593
  • 24
  • 91
  • 160
  • What is jQuery deferred? – Jordan Baron May 15 '18 at 13:50
  • @JordanBaron [deferred](http://api.jquery.com/category/deferred-object/) is a promise like object that jQuery created before the Promise standard was finalized, especially older implementations of it have behaviors that are not like standard promises as we now know today. Even if you want to support Internet Explorer (does not have native Promises) I'd advice getting a good polyfil and wrap the deferred in a `Promise.resolve(some deferred like $.ajax(...))`. – HMR May 15 '18 at 15:08