Professional Documents
Culture Documents
Lesson 7 - Asynchronous Functions and API
Lesson 7 - Asynchronous Functions and API
calls
Introduction
var data =
networkRequest(“www.someurl.com”);
greeting() is executed
immediately, so data will be
greeting(data);
undefined.
Using callbacks
networkRequest 2nd
const networkRequest = (url, callback) => { parameter is callback,
/* connect to some server and get data */ which should be a
//somedata is retrieved from the server function.
callback is called
callback(somedata); when function is
} completed
}
step1(1, this.step2);
Introduction to Promises
fetch(‘http://example.com/test.json’)
.then(response => response.json())
.then(data => console.log(data));
Using Fetch Api
Fetching data from data.gov.sg
Moment is a library for parsing dates and times
(www.momentjs.com)
var today = moment().format(“YYYY-MM-DD”);
fetch(“https://api.data.gov.sg/v1/environment/psi?date=“+today, {
method:’GET’}
).then(response => response.json())
.then(data => {
Using callbacks:
fetch(“/server/call1”).then(response => {
fetch(“/server/call2”).then(response2 => {
fetch(“/server/call3”).then(response3 =>{
var z = response + response2 + response3;
}
}
});
Async and await
var number = 0;
var data = [50, 100, 150];
async function delay(){
return new Promise(resolve => setTimeout(resolve, 300));
}
console.log(number);
Loops with Promises
2. Using a for-loop processes the array in sequence
Output:
50
150
300
300
Loops with Promises