?print-pdf' Created by
// generate array of integers - needed for tests bellow:
let testArrays = [
Array.from({length:1_000_000},(_,i)=>i+1),
Array.from({length:2_000_000},(_,i)=>i+1),
Array.from({length:3_000_000},(_,i)=>i+1),
];
function syncDemo(){
console.time('syncDemo');
testArrays.forEach(arr=>{
console.log(arr.reduce((ac, el)=>ac+el));
})
console.timeEnd('syncDemo');
}
function asyncDemo(){
//setTimeout is executed asynchronous and is not blocking the rest of the code!
console.time('asyncDemo');
testArrays.forEach(arr=>{
setTimeout(()=>{console.log( arr.reduce((ac, el)=>ac+el) )}, 0)
})
console.timeEnd('asyncDemo');
}
console.log(`~~~~~ Sync execution ~~~~~`);
syncDemo();
console.log(`\n~~~~~ Async execution ~~~~~`);
asyncDemo();
// ~~~~~ Sync execution ~~~~~
// 500000500000
// 2000001000000
// 4500001500000
// syncDemo: 176.295ms
//
// ~~~~~ Async execution ~~~~~
// asyncDemo: 0.411ms
// 500000500000
// 2000001000000
// 4500001500000
then() calls)
// create Promise object:
const p = new Promise((resolve, reject)=>{
// do promised work asynchronously, like getting data
setTimeout(() => {
const data = 'some data';
if(data){
resolve(data)
}else{
reject('Error')
}
}, 1000);
});
// use promise:
p.then(value => {
console.log(value);
}, reason => {
console.error(reason);
});
let getDataPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Some data');
// reject('Error message');
}, 1000);
});
async function renderData() {
try {
const data = await getDataPromise
console.log(data);
} catch (error) {
console.error(error);
}
}
renderData();
let getDataPromise = new Promise((resolve, reject) => {
setTimeout(() => {
// resolve('Some data');
reject('Can not get data!');
}, 1000);
});
// using getDataPromise with Async/Await API:
async function renderData() {
try {
const data = await getDataPromise
console.log(data);
} catch (error) {
console.error(error);
}
}
// using getDataPromise with Promise API:
function renderData() {
getDataPromise
.then(data=>console.log(data))
.catch(err=>console.log(err))
}
renderData();
These slides are based on
customised version of
framework