this syntax uses the async and await keywords to enable writing asynchronous code that closely resembles synchronous code patterns. For this reason, code using async and await is widely recognized as being easier for humans to parse than code using promises. You use the async keyword as part of a function declaration or expression to specify that the function should be executed asynchronously. That is, it should not block the parser's main process. Within an asynchronous function, you use the await keyword before a statement that returns a promise to indicate that the function should stop and wait for the result of the promise before proceeding. It's important to understand that aside from a couple details, async and await are essentially just syntactic sugar, meaning that they simply provide shorthand syntax for writing code using an existing coding practice. In this case, async and await code creates and works with promises under the hood. So for many situations, you can write simpler code using async and await instead of expressly writing promises and still get the same results.
what's happening here in our function is a combination of synchronous and asynchronous statements. So, we're starting out with the synchronous statement just creating an array. Now, these next four statements all involve an asynchronous request through this get function. And so, all four of these await statements will start at the same time. So, they're all going to run in parallel. But then we get to our next synchronous statement and that is what's going to wait for the results of all of these other statements. And so, once we get responses from all four of those requests, then this synchronous code here is going to run here and here and then we're all done.
You enclose your statements in a try block and then add a catch block afterward that specifies a parameter name for the error object .
function get(url) {
return new Promise(function(resolve, reject) {
let httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url);
httpRequest.onload = function() {
if (httpRequest.status === 200) {
// Resolve the promise with the response text
// success(httpRequest.responseText);
resolve(httpRequest.response);
} else {
// Reject the promise with the status text
// fail(httpRequest.status);
reject(Error(httpRequest.statusText));
}
};
// Handle network errors
httpRequest.onerror = function() {
reject(Error('Network Error'));
};
httpRequest.send();
});
}
function successHandler(data) {
const dataObj = JSON.parse(data);
// const weatherDiv = document.querySelector('#weather');
const div = `
${dataObj.name}
${tempToF(dataObj.main.temp)}° |
${dataObj.weather[0].description}
`;
return div;
// weatherDiv.innerHTML = weatherFragment;
}
function failHandler(status) {
console.log(status);
}
function tempToF(kelvin) {
return ((kelvin - 273.15) * 1.8 + 32).toFixed(0);
}
document.addEventListener('DOMContentLoaded', function() {
const apiKey = 'd126cacbbfebf7c84ad878e9deffc0e1';
//const apiKey = '';
const weatherDiv = document.querySelector('#weather');
const locations = [
'los+angeles,us',
'san+francisco,us',
'lone+pine,us',
'mariposa,us'
];
const urls = locations.map(function(location) {
return `https://api.openweathermap.org/data/2.5/weather?q=${location}&APPID=${apiKey}`;
});
// get(url, successHandler, failHandler);
// Promise.all([get(urls[0]), get(urls[1]), get(urls[2]), get(urls[3])])
// .then(function(responses) {
// return responses.map(function(response) {
// return successHandler(response);
// });
// })
// .then(function(literals) {
// weatherDiv.innerHTML = `Weather
${literals.join('')}`;
// })
// .catch(function(status) {
// failHandler(status);
// })
// .finally(function() {
// weatherDiv.classList.remove('hidden');
// });
(async function() {
try {
let responses = [];
responses.push(await get(urls[0]));
responses.push(await get(urls[1]));
responses.push(await get(urls[2]));
responses.push(await get(urls[3]));
let literals = responses.map(function(response) {
return successHandler(response);
});
weatherDiv.innerHTML = `Weather
${literals.join('')}`;
} catch (status) {
failHandler(status);
} finally {
weatherDiv.classList.remove('hidden');
}
})();
});
And so now, everything in here will be an async function. It will also be immediately invoked when it's declared.
So, we're going to go responses.push and then I want to make a call to the get function, passing at the first URL in my urls array. And so, to do that, I'm just going to type get urls[0] and now, what I want is for my async function to wait for the result of that get request before it moves on to other code.And do to that, I just preface the get call with await. And so, this is going to grab the first URL in my array, which will be for Los Angeles. It's going to send it to the get function that we've been using, that we built. And then, when it gets data back, it's going to push that data to the responses array and then it will move on to the next line. So, I just want to repeat that three times for all the items in that array. So, I'm just going to copy and paste that statement three times and change my index number and clearly, I could do this with some sort of a loop, but in order to really see how async and await are working here, I think it's useful to make these individual statements and see how they're executed.