Returning the $.get
function is a promise, so you can use the done
method whenever you want to use the returned return. For example, below I have done that as soon as the page loads the tweets list is displayed on the screen using the done
method. In this case, it is equivalent to using the anonymous function as callback .
You can read more here: What to use in Ajax, success or done?
Interest is that when you press the button, the tweets are listed in an orderly fashion. For simplicity, I ordered the id
returned by the server. Notice that in the event handling click
I again used the done
of promise method. This method works like this: Given an asynchronous event, in this case the request, the done
method invokes the callback function passed to it when the event is terminated; if a new callback function is passed after the event is finalized, the function is executed promptly. In this example, to list the tweets , the function will wait for the request to be completed, and when you press the button, the order will be executed immediately,
Actually, even if the request has not yet been terminated when the button is pressed, the operation would be the same, since the callback and callback functions would be invoked in this order, generating the same result.
$(() => {
const ul = $("ul");
const button = $("button");
const tweets = $.get("https://api-nave-twitter.herokuapp.com/tweets");
tweets.done(function (data) {
$(data).each(function (index, tweet) {
ul.append($("<li>").text(tweet.text));
});
});
button.on("click", function (event) {
tweets.done(function (data) {
let sorted = data.sort((a, b) => a.id <= b.id);
ul.empty();
$(data).each(function (index, tweet) {
ul.append($("<li>").text(tweet.text));
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
<button>Ordenar por id</button>