JS Promises
JavascriptWhat is a Promise?
A Promise is a way to handle asynchronous operations in JavaScript. It represents a value that may be available now, later, or never.
Creating a Promise
let mypromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000);
});
Using Promises
mypromise.then(result => {
console.log(result); // "done!"
}).catch(error => {
console.error(error);
});
Async/Await
async function run() {
let result = await mypromise;
console.log(result);
}
Simple Sleep
async function sleep(time=2000){
return await new Promise(r => setTimeout(r, time));
}
let s = await sleep();
Simultaneous Awaits
async function run() {
let [res1, res2] = await Promise.all([func1(), func2()]);
console.log(res1);
console.log(res2);
}