Async and Await in JavaScript

The async keyword

let hello = async function() { return "Hello" };
hello();

The await keyword

fetch('coffee.jpg')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
return response.blob();
}
})
.then(myBlob => {
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
})
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});

Async / Await in React

async componentDidMount() {
const response = await fetch(`https://api.com/v1/ticker/?limit=10`);
const json = await response.json();
this.setState({ data: json });
}

More Effective way to write code in ASYNC and AWAIT

async componentDidMount() {
try {
const response = await fetch(`https://api.com/v1/ticker/?limit=10`);
const json = await response.json();
this.setState({ data: json });
} catch (error) {
console.log(error);
}
}

Conclusion

Full-stack Web Developer, loves to travel, party, read, write, crowd speaking and code