ES2015 generators for async
by ptitgraig
HTML
<script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
<h3 id="title">
</h3>
<p id="body">
</p>
<hr>
JavaScript
function getPostById(postId) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/"+postId,
context: document.body
}).always(function(data, status) {
if (status === "error") {
it.throw(status);
} else {
it.next(data);
}
});
}
function *main() {
try {
// async code that looks like sync !!
var post = yield getPostById(1);
$('#title').text(post.title);
$('#body').text(post.body);
} catch (err) {
console.error(err);
}
}
var it = main();
it.next(); // start the generator