Skip to content

Instantly share code, notes, and snippets.

@Onatcer

Onatcer/babel.js Secret

Last active February 2, 2017 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Onatcer/a01afa3b81054d0bbd05a450af02a54e to your computer and use it in GitHub Desktop.
Save Onatcer/a01afa3b81054d0bbd05a450af02a54e to your computer and use it in GitHub Desktop.
Fetch and Async Await
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
(async() => {
try {
let response = await fetch("http://localhost:8080/api/v1/demo/nodes/bd753cc9b07246e0b53cc9b072f6e070/children", {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Basic '+btoa('admin:admin')
}
});
let automobiles = await response.json();
let data = automobiles.data;
data.map(function(data) {
$('body').append('<h3>' + data.fields.name + '</h3>' +
'<li>' + data.fields.description + '</li>' +
'<li> <strong>Price:</strong> ' + data.fields.price + '$</li>');
});
} catch (e) {
console.log("Something went wrong!");
}
})();
</script>

Source: https://pixabay.com/en/adorable-animal-canine-cute-dog-1849992/

Alternativen:

Titelvorschläge:

  • Make AJAX-Requests Great Again: Perform requests with the Fetch API and Async/Await (ES2017)
  • How to use API-first CMS Gentics Mesh with the Fetch API and Async/Await (ES2017)
  • Getting started with the Fetch API and Async/Await (ES2017) for our API-first CMS Gentics Mesh
  • Requesting Data from our API-first CMS Gentics Mesh with the Fetch API and Async/Await (ES2017)

Teaser-Text: AJAX Requests are often handled by third party libraries, because of the unpopular native XMLHttpRequest feature in JavaScript. With the File API and ES2017 features like Async/Await this could change now. In this blogpost we show you how to perform AJAX requests to our API-first CMS Gentics Mesh, using the File API and Async/Await with the use of Babel.js.

Until recently, XMLHttpRequests were the only way to send AJAX Requests in vanilla JavaScript. Because they were not intended to be used as extensively as they are used nowadays (and because of its ugly syntax) developers used frameworks and libraries to get around this problem. The most popular methods are probably jQuery's jQuery.ajax() functions. Lately a new API has a emerged which aims to replace XMLHttpRequest: the Fetch API. It is now supported by most of the popular browsers out there. In this blogpost we show you how to use the Fetch API and the new Async/Await-Features of ES2017 with our API-first CMS Gentics Mesh.

Gentics Mesh provides API endpoints for us to fetch data from. To get started we need to download and start the Gentics Mesh Server.

HTML: <a class="btn btn-primary" style="margin: 0 auto" href="http://getmesh.io/Download">Get the latest version of Mesh here!</a>

Save the file to a new empty folder and enter $ java -jar mesh-demo-0.6.xx.jar into your terminal to start the Gentics Mesh Server. Once started, you should be able to see our API-first CMS running on http://localhost:8080.

For this blogpost we'll work with the demo-project which is automatically included in every new Mesh setup.

The Fetch API

Let's look at the basic structure of a Fetch API Request first:

  <script src="https://gist.github.com/Onatcer/a01afa3b81054d0bbd05a450af02a54e.js?file=fetch1.js"></script>

To communicate with the Gentics Mesh API we need to send an Authorization header and some other headers with our requests. We define these options in a new object so we can reuse them later.

<script src="https://gist.github.com/Onatcer/a01afa3b81054d0bbd05a450af02a54e.js?file=fetch2.js"></script>

We simply pass this object over to our fetch function and set the API-Endpoint we want to request data from. For demonstration, we'll do a GET-Request to /nodes which returns all nodes of our demo project.

<script src="https://gist.github.com/Onatcer/a01afa3b81054d0bbd05a450af02a54e.js?file=fetch3.js"></script>

It's time to print the received data, so the user can see it in the browser window. To do that we are fetching data from the /nodes/bd753cc9b07246e0b53cc9b072f6e070/children-Endpoint which returns all automobiles of our demo project (bd753cc9b07246e0b53cc9b072f6e070 is the UUID of the "Automobiles" category and all automobiles are children of this folder. The UUID won't be the same in your instance of Gentics Mesh).

<script src="https://gist.github.com/Onatcer/a01afa3b81054d0bbd05a450af02a54e.js?file=fetch4.js"></script>

As a result you should get something like this:

Async/Await in ES2017

EcmaScript 7 provides us with an even more elegant way to fetch data with its Async/Await-Features. Since ES2017 is not yet supported by many major browsers, we need to use Babel. Babel essentially compiles next generation ECMAScript Code to JavaScript that most browsers are able to execute. Basically it enables you to write modern code, that will be supported by browsers natively in the future, without thinking about browser support.

There are many ways to include Babel in your setup as you can see on their setup page. To just try it out you can include their JS-File in your HTML with <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>. This is of course not meant for production.

<script src="https://gist.github.com/Onatcer/a01afa3b81054d0bbd05a450af02a54e.js?file=babel.js"></script>

As you can see in the example, there is no need for then blocks anymore. We can simply await the fetch request and other functions to execute before continuing. It makes the code more clean and more readable.

Conclusion

The Fetch API and ES2017 Async/Await-Features can be used to improve the quality and readability of the code. As you can see on CanIUse, the Fetch API is pretty good supported among modern browsers. In production, you might want to use one of the available polyfills anyway.

ES2017, on the other side, lacks native browser support. So if you want to program next-gen ECMAScript and can easily integrate Babel into your setup: go for it! Otherwise, you are probably better off using the Fetch-API. It really depends on the use case here.

Feel free to drop a comment if you have and questions or feedback about the shown implementation. And also don't forget to download our API-first CMS Gentics Mesh!

fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
// Your code for handling the data you get from the API
})
.catch(function() {
// This is where you run code if the server returns any errors
});
var obj = {
method: 'GET',
headers: {
'Authorization': 'Basic '+btoa('webclient:webclient'),
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
fetch("http://localhost:8080/api/v1/demo/nodes", obj).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function() {
console.log("Something went wrong!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
...
<script type="text/javascript">
fetch("http://localhost:8080/api/v1/demo/nodes/bd753cc9b07246e0b53cc9b072f6e070/children", obj)
.then(function(response) {
return response.json();
}).then(function(automobiles) {
data = automobiles.data;
return data.map(function(data) {
$('body').append('<h3>' + data.fields.name + '</h3>' +
'<li>' + data.fields.description + '</li>' +
'<li> <strong>Price:</strong> ' + data.fields.price + '$</li>');
});
})
.catch(function() {
console.log("Something went wrong!");
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment