Early in this book, we mentioned the async/await syntax. I remember the time when this API came to the language. Our code became a bit easier to read and manage. There is one caveat, though - we can't use await
in the global scope. In such cases, we have to use a self-invoked async function.
const url = "https://api.thecatapi.com/v1/images/search";
(async function getData() {
const res = await fetch(url);
const data = await res.json();
console.log(data[0].url); // cat image url
})();
This pattern is also known as IIFE (Immediately Invoked Function Expression). It is helpful for the cases where we want to wrap logic in its dedicated scope. In the example above, res
and data
constants are only accessible inside the getData
function.
(It is possible that the JavaScript engine that you are using supports a top-level await
. So, you may not need a self-invoked function.)