Promises
Promises
Promises
//Synchronous code
console.log("start")
console.log("Subscribe to Roadside Coder")
console.log("stop")
setTimeout(() => {
console.log("Subscribe to Roadside Coder");
}, 2000);
console.log("stop");
// Asnychronous Example
console.log("start")
function importantAction(username) {
setTimeout(() => {
return `Subscribe to ${username}`;
}, 1000);
}
console.log("stop");
// Callback
console.log("start")
console.log("stop")
// Callback Hell
console.log("start")
console.log("stop")
// Promises
console.log("start");
sub
.then((message) => {
console.log(message);
})
.catch((err) => {
console.log(err);
});
console.log("stop");
// Rewriting Callbacks
console.log("start");
function importantAction(username) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Subscribe to ${username}`);
}, 1000);
});
}
function likeTheVideo(video) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Like the ${video} video`);
}, 1000);
});
}
function shareTheVideo(video) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Share the ${video} video`);
}, 1000);
});
}
console.log("stop");
// Promise Chaining
// Promise Combinator
// promise.all()
console.log("start")
Promise.all([
importantAction("Roadside Coder"),
likeTheVideo("Javascript Interview Questions"),
shareTheVideo("Javascript Interview Questions")
]).then((res)=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
console.log("stop")
// promise.race()
console.log("start")
Promise.race([
importantAction("Roadside Coder"),
likeTheVideo("Javascript Interview Questions"),
shareTheVideo("Javascript Interview Questions")
]).then((res)=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
console.log("stop")
// promise.allSettled()
console.log("start")
Promise.allSettled([
importantAction("Roadside Coder"),
likeTheVideo("Javascript Interview Questions"),
shareTheVideo("Javascript Interview Questions")
]).then((res)=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
console.log("stop")
// promise.any()
console.log("start")
Promise.any([
importantAction("Roadside Coder"),
likeTheVideo("Javascript Interview Questions"),
shareTheVideo("Javascript Interview Questions")
]).then((res)=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
console.log("stop");
result();
console.log('start');
promise1.then(res => {
console.log(res)
})
console.log('end');
console.log('start');
promise1.then(res => {
console.log(res)
})
console.log('end');
console.log('start')
console.log('middle')
fn().then(res => {
console.log(res)
})
console.log('end')
function job() {
return new Promise(function(resolve, reject) {
reject();
});
}
promise
.then(function() {
console.log('Success 1');
})
.then(function() {
console.log('Success 2');
})
.then(function() {
console.log('Success 3');
})
.catch(function() {
console.log('Error 1');
})
.then(function() {
console.log('Success 4');
});
function job(state) {
return new Promise(function(resolve, reject) {
if (state) {
resolve('success');
} else {
reject('error');
}
});
}
promise
.then(function(data) {
console.log(data);
return job(false);
})
.catch(function(error) {
console.log(error);
.then(function(data) {
console.log(data);
return job(true);
})
.catch(function(error) {
console.log(error);
});
function job(state) {
return new Promise(function(resolve, reject) {
if (state) {
resolve('success');
} else {
reject('error');
}
});
}
promise
.then(function(data) {
console.log(data);
return job(true);
})
.then(function(data) {
if (data !== 'victory') {
throw 'Defeat';
}
return job(true);
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
return job(false);
})
.then(function(data) {
console.log(data);
return job(true);
})
.catch(function(error) {
console.log(error);
return 'Error caught';
})
.then(function(data) {
console.log(data);
return new Error('test'); // Not Returning a promise
})
.then(function(data) {
console.log('Success:', data.message);
})
.catch(function(data) {
console.log('Error:', data.message);
});
const secondPromise = new Promise((resolve, reject) => { In .then(res => res), the function inside .then() is a bit peculiar. It's
resolve(firstPromise); essentially saying, "Take whatever you got (represented by res)
}) and give it back as it is." So, it's like a "pass-through" or "echo"
function. Whatever comes in, goes out unchanged. It doesn't
secondPromise modify or do anything with res, just passes it along to the next
.then(res => res) step in the chain.
.then(res => console.log(res));
function loadJson(url) {
return fetch(url)
.then(response => {
if (response.status == 200) {
return response.json();
} else {
throw new Error(response.status);
}
});
}
loadJson('https://javascript.info/no-such-user.json').catch(alert);
// Answer
async function loadJson(url) { // (1)
let response = await fetch(url); // (2)
if (response.status == 200) {
let json = await response.json(); // (3)
return json;
}
loadJson('https://javascript.info/no-such-user.json').catch(alert);
function importantAction(username) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Subscribe to ${username}`);
}, 1000);
});
}
function likeTheVideo(video) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Like the ${video} video`);
}, 1000);
});
}
function shareTheVideo(video) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Share the ${video} video`);
}, 1000);
});
}
function promRecurse(funcPromises) {
if (funcPromises.length === 0) return;
const promi = funcPromises.shift();
promRecurse(funcPromises);
}
promRecurse([
importantAction("Roadside Coder"),
likeTheVideo("Javascript Interview Questions"),
shareTheVideo("Javascript Interview Questions"),
]);
function PromisePolyFill(executor) {
let onResolve,
onReject,
fulfilled = false,
rejected = false,
called = false,
value;
function resolve(v) {
fulfilled = true;
value = v;
function reject(reason) {
rejected = true;
value = reason;
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
promise1.then(res => {
console.log(res)
});
// promise.all()