Reggie
Reggie

Reputation: 79

Run function after other function completes

I want to run the a function after another function completes. I've found the way below of achieving it but my issue is that I want to use the output of the getLocation function as the argument for the update function, station in this case.

Is there a way I can run the code like this and assign a variable to the output of the getLocation function?

function giveAddress(){
    $.getJSON('http://localhost:5000/api/stations', function(json) {
        {
            $.when($.ajax(getLocation(json))).then(function () {
                update(station);
            });
        })
    }

Any help is greatly appreciated.

Upvotes: 1

Views: 248

Answers (3)

Zohra Gadiwala
Zohra Gadiwala

Reputation: 216

The only thing you need to do is just take the response that your function getLocation is returning in the promise .then() and pass it to the update function

function giveAddress(){
  $.getJSON('http://localhost:5000/api/stations', function(json) {
  {
     $.when($.ajax(getLocation(json))).then(function (response) {
       update(response);
     });
  })
}

Upvotes: 0

cнŝdk
cнŝdk

Reputation: 32145

You are almost there, you just need to add a data argument to the promise then callback function and then pass it to your second function:

function giveAddress(){
$.getJSON('http://localhost:5000/api/stations', function(json) {
    {
        $.when($.ajax(getLocation(json))).then(function (data) {
            update(data);
        });
    })
}

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Do not use callbacks if you have Promises

function giveAddress(){
    return $
     .getJSON('http://localhost:5000/api/stations') // first request
     .then(getLocation) // extract location
     .then(function(location) {
       return $.ajax(location)
         .then(function(){return location}) // second request still return location
     })
     .then(update)
}

or if you need to use the result of getting location

function giveAddress(){
    return $
     .getJSON('http://localhost:5000/api/stations') // first request
     .then(getLocation) // extract location
     .then(function(location) {
       return $.ajax(location)
         .then(function(data){return {
            location: location,
            data: data}
         }) // keep location and data
     })
     .then(function(result) {
       // use result.data 
       update(result.location)
     })
}

Upvotes: 3

Related Questions