Skip to content

Instantly share code, notes, and snippets.

@iamaakashbasnet
Last active October 26, 2023 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamaakashbasnet/6af6d0629ec74cb8cee8afa674f7d8c2 to your computer and use it in GitHub Desktop.
Save iamaakashbasnet/6af6d0629ec74cb8cee8afa674f7d8c2 to your computer and use it in GitHub Desktop.
Async JS
const posts = [
{
id: 1,
title: 'Post One',
body: 'This is post one'
},
{
id: 2,
title: 'Post Two',
body: 'This is post two'
}
];
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post, index) => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function createPost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = true;
if (!error) resolve();
else reject('Something went wrong!');
}, 2000);
});
}
async function init() {
try {
await createPost({
id: 3,
title: 'Post Three',
body: 'This is post three'
});
getPosts();
} catch (err) {
console.log(err);
}
};
init();
const posts = [
{
id: 1,
title: 'Post One',
body: 'This is post one'
},
{
id: 2,
title: 'Post Two',
body: 'This is post two'
}
];
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post, index) => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function createPost(post, callback) {
setTimeout(() => {
posts.push(post);
callback();
}, 2000);
}
getPosts();
createPost({
id: 3,
title: 'Post Three',
body: 'This is post three'
}, getPosts);
const posts = [
{
id: 1,
title: 'Post One',
body: 'This is post one'
},
{
id: 2,
title: 'Post Two',
body: 'This is post two'
}
];
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post, index) => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function createPost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = true;
if (!error) resolve();
else reject('Something went wrong!');
}, 2000);
});
}
getPosts();
createPost({
id: 3,
title: 'Post Three',
body: 'This is post three'
})
.then(getPosts)
.catch(err => console.log(err));
// Promise.all([promise1, promise2, promise3]).then(vals => console.log(vals));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment