Short introduction to async-await, with fetch

node v4.9.1
version: 1.0.0
In JavaScript, many functions have asynchronous execution. Operations requiring disk or network access are usually asynchronous. This means that they execute in the background, and return the results at a later stage. Asynchronous functions typically return a Promise` object. A Promise represents a value that may be returned in the future - typically after the request has completed. One example of an asynchronous call is the fetch API, which can be used to make HTTP requests. There are two ways to get the value of a Promise. The first is to call .then() with a callback function, which will be called when the value is ready.
var fetch = require('node-fetch'); fetch("").then(function(response) { console.log('Success (Promise)? ' + response.ok); });
An easier way is to use the `await` keyword. To use await, the function must be defined as an async function.
var response = await fetch(""); console.log('Success (await)? ' + response.ok);
Note: response contains the status and headers of the response, but not the body yet. To get the body, we call response.json(), which is again synchronous:
var body = await response.json(); body
Note that if we omit the await keyword the function will still execute in the background, but we won't get the results. To use await in functions, the function must be defined as asynchronous with the async keyword. This in turn makes the function return a Promise.
async function getLocation() { var response = await fetch(""); var body = await response.json(); return body; } await getLocation()
Error handling can be performed with try...catch, same as in normal JavaScript:
try { var response = await fetch("http://imadeatypo"); } catch(error) { console.log('Request failed:', error); }
Further reading:

no comments

    sign in to comment