Laying foundations to Promises
13.8 billion years ago, universe expanded from a singularity giving birth to galaxies, stars, planets, life and TIME!
Now JavaScript and Browsers need to deal with this relic.
Photo by Jeremy Thomas on Unsplash
console.log("print first");
setTimeout(secondPrint,0); // 0 DELAY
setTimeout(thirdPrint,10);
console.log("print fourth");
function secondPrint(){
console.log("print second");
}
function thirdPrint(){
console.log("print third");
}
// print first
// print second
// print third
// print fourth
// print first
// print fourth
// print second
// print third
// print first
// print second
// print fourth
// print third
A.
B.
C.
Console
Stack
Heap
Queue
console.log("print first");
setTimeout(secondPrint,0);
setTimeout(thirdPrint,10);
console.log("print fourth");
console.log("print first");
setTimeout(secondPrint,0);
setTimeout(thirdPrint,10);
console.log("print fourth");
Console
Stack (Main Thread)
Heap
Queue
"print first"
setTimeout(secondPrint,0);
setTimeout(thirdPrint,10);
console.log("print fourth");
Console
Stack (Main Thread)
Heap
Queue
"print first"
setTimeout(thirdPrint,10);
setTimeout(secondPrint,0);
console.log("print fourth");
Console
Stack (Main Thread)
Heap
Queue
"print first"
setTimeout(thirdPrint,10);
console.log("print fourth");
secondPrint
Console
Stack (Main Thread)
Heap
Queue
"print first"
console.log("print fourth");
setTimeout(thirdPrint,10);
secondPrint
Console
Stack (Main Thread)
Heap
Queue
"print first"
"print fourth"
secondPrint
<empty>
thirdPrint
Console
Stack (Main Thread)
Heap
Queue
"print first"
"print fourth"
"print second"
thirdPrint
<empty>
<empty>
Console
Stack (Main Thread)
Heap
Queue
"print first"
"print fourth"
"print second"
"print third"
<empty>
<empty>
<empty>
Console
Stack (Main Thread)
Heap
Queue
console.log("print first");
setTimeout(secondPrint,0); // 0 DELAY
setTimeout(thirdPrint,10);
console.log("print fourth");
function secondPrint(){
console.log("print second");
}
function thirdPrint(){
console.log("print third");
}
// print first
// print fourth
// print second
// print third
B.
while(browser.alive){
if(stack.empty && !queue.empty){
stack.push(queue.next)
}
}
@MDN
let coordinates;
navigator
.geolocation
.getCurrentPosition((position)=>{
coordinates=position;
});
console.log(coordinates);
let coordinates;
//navigator
// .geolocation
// .getCurrentPosition((position)=>{
// coordinates=position;
//});
console.log(coordinates);
.getCurrentPosition((position)=>{
getWeather(position,(weather)=>{
getIcon(status,(success)=>{
//display weather
},handleIconError);
},handleWeatherError)
},handlePositionError);
$.ajax({
url: apiURL,
success: data=>{
//valid data from HTTP
console.log('success',data);
},
error: (xhr,status)=>{
//HTTP or parsing error
console.log('error',status);
}
});
fetch(apiURL)
.then(validate)
.then(data => console.log('success',data))
.catch(error => console.log('error',error));
getCoordinates
.then(getWeather)
.then(getIcon)
.then(displayResult)
.catch(handleError);
const p = new Promise((resolve, reject) => {
//asynchronous activity
//call resolve when things go ok
//call reject on error
});
promise
.then(resolveFunction)
.catch(rejectFunction);
function resolveFunction(data) {
//process data
}
function rejectFunction(error) {
// handle error
}
Create an already resolved promise
let p1=Promise.resolve(2);
let p2=Promise.resolve(p1);
p1.then(console.log);//2
p2.then(console.log); //2 !!
Create an already rejected promise
let p1=Promise.reject(2);
let p2=Promise.resolve(p1);
p1.then(x=>x*x)
.catch(e=>console.log("Err:", e));
//Err:2
p2.then(x=>x*x)
.catch(e=>console.log("Err:", e));
//Err:2
let data=fetch(url); // network request
//do
//hundred
//other
//things
data.then(worksOK);
let p1=Promise.resolve(2);
p1.then(x=>x*x)
.then(console.log); //4
p1.then(console.log); //2 !!
let result=fetch(url);
result
.then(res => res.json())
.then(console.log);
//oh, I want to reuse that result again
result
.then(res=>res.json())
.then(processJSON);
//TypeError; body stream already read
let result=fetch(url);
result
.then(response=>response.clone())
.then(res => res.json())
.then(console.log);
//oh, I want to reuse that result again
result
.then(res=>res.json())
.then(processJSON);
promise
.then(process,initialErrors)
.then(transform)
.catch(handle)
.then(display)
.catch(inform);
let promise=Promise.resolve(2);
promise
.then(x=>x*x)
.then(console.log);//4
let p1=Promise.resolve(2);
p1
.then(x=>x*x) // 4
.then(x=>[x**x]) // [256]
.then(x=>x.toString()) // 256
.then(x=>x.split('')) // ["2","5","6"]
.then(console.log); // ["2","5","6"]
let promise=Promise.resolve(2);
promise
.then(x=>x*x)
.then(console.log) //4
.then(console.log); //undefined!
let promise=Promise.resolve(2);
promise
.then(x=>x*x)
.then(x=>{
console.log(x);
return x; //✌
) //4
.then(console.log); //4!
let p=Promise.resolve(2);
p.then(callback1)
.catch(errorHandler1)
.finally(()=>{
// clean up
// inform
//wind up
});
//⚠: BROWSER SUPPORT
let p=Promise.resolve("promise");
setTimeout(console.log,0,"timeout");
p.then(console.log);
console.log("insider");
// insider
// promise 🔥
// timeout
async function fun(){
await Promise.resolve(1);
console.log("fun");
}
function syncTest(){
fun();
console.log("after");
}
syncTest();
//after
//fun
async function asyncTest(){
await fun();
console.log("after");
}
asyncTest();
//fun
//after