Async Action handling in Javascript

Garud Pragati
Feb 23 · 4 min read
  let promise = new Promise((resolve, reject) => {
// do a thing, if everything is fine then resolve
// otherwise reject
})

//Success handler executed on promise resolve
promise.then((data) => console.log(data));

//Error handler executed on promise reject
promise.catch((error) => console.log(error));
const fetchData = () => {
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
}
fetchData();
const fetchData = () => {
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
})
}
fetchData();
async function f() {
// await works only inside async functions
let value = await promise;
return 1;
}
async function f() {
// await works only inside async functions
let value = await promise;
return Promise.resolve(1);
}
const fetchData = async () => {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/users');
let data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
fetchData();
function* generator() {
// do something
yield expression;
}
function* generator() {
yield 5+3;
yield 7*2;
}

let it = generator(); // does not start execution of function body
console.log(it.next()); // { value: 8, done: false }
console.log(it.next()); // { value: 14, done: false }
console.log(it.next()); // { value: undefined, done: true }
function* fetchData() {
try {
let response = yield fetch('https://jsonplaceholder.typicode.com/users');
let data = yield response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
let it = fetchData();// { value: promise returned by fetch(), done: false }
let promise1 = it.next().value
promise1.then((response) => {//resume generator by calling next() as your async operation is fulfilled now.
// we can pass values to generator from here. e.g response is accessible here but we need that in the generator, passed value will gets assign to response variable of the generator.
//{ value: promise returned json(), done: false }
let promise2 = it.next(response).value promise2.then((data) => {
it.next(data);
});
});

Garud Pragati

Written by

Software developer(ReactJs)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade