Created
March 15, 2016 17:15
-
-
Save courtneyphillips/ab38629fb1935f9eef62 to your computer and use it in GitHub Desktop.
Async API Calls in Node Modules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Because the ajax request is asynchronous, cannot assign data from api response to a variable in the success | |
// callback and return it, because the return statement will execute before the success function is completed. | |
// Instead, logic must happen inside of the success callback function. | |
// This can either mean using jQuery to directly display the response: | |
exports.getHumidity = function(city) { | |
$.get(url).then(function(response) { | |
$('.showWeather').text("The humidity in " + city + " is " + response.main.humidity + "%"); | |
}).fail(function(error) { | |
$('.showWeather').text(error.message); | |
}); | |
}; | |
// Or it can be done by passing in display functions as arguments: | |
exports.displaySuccess = function(apiData) { | |
console.log("Yay! Call succeeded. ", apiData); | |
} | |
exports.displayError = function(err) { | |
console.log("Noooo! Failure!!!" , err.message); | |
} | |
exports.getHumidity = function(city) { | |
$.get(url).then(function(response) { | |
exports.displaySuccess(response); | |
}).fail(function(error) { | |
exports.displayError(error); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment