Async Javascript
Async Javascript
let fs = require('fs');
console.log('1');
console.log('2');
});
console.log('3');
a. 123
b. 321
c. 231
d. 132
a. first!
b. done!
c. Javascript error
d. Something else
let x = 0;
async function test() {
x += await 2;
console.log(x);
}
test();
x += 1;
console.log(x);
a. 21
b. 1 undefined
c. 12
d. null 1
a. error
b. Oh-oh
c. Undefined
d. Null
a. Success SUCCESS
b. SUCCESS
c. Success
d. Nothing prints
a. SUCCESS SUCCESS
b. SUCCESS
c. Success
d. Nothing prints
Promise.resolve('Success!')
.then(data => {
data.toUpperCase()
})
.then(data => {
console.log(data)
})
a. SUCCESS SUCCESS
b. SUCCESS
c. Success
d. Nothing prints
Promise.resolve('Success!')
.then(() => {
throw Error('Oh noes!')
})
.catch(error => {
return 'actually, that worked'
})
.then(data => {
throw Error('The fails!')
})
.catch(error => console.log(error.message))
a. Oh noes! , The fails!
b. Oh noes!
c. The fails!
d. Nothing prints
17. What are the different ways to deal with Asynchronous Code
Below are the list of different ways to deal with Asynchronous code.
i. Callbacks
ii. Promises
iii. Async/await
iv. Third-party libraries such as async.js, bluebird etc
The asynchronous thunks are useful to make network requests. Let's see an
example of network requests,
async2(function(){
async3(function(){
async4(function(){
....
});
});
});
});
function getPosts(){
setTimeout(() => {
posts.forEach((post, index)=> {
});
document.body.innerHTML = output;
}, 1000);
// Callbacks
posts.push(post);
callback();
}, 2000);
// promises
function createPost(post){
setTimeout(()=>{
posts.push(post);
if(!error){
resolve();
else{
reject(Error(""h
}, 2000)
})
.then(getPosts)
// promise.all
const p1 = Promise.resolve("name");
const p2 = 10;
//async await
getPosts();
init();
O/P: