Created by Haroldas Zapalskis & Aidas Klimas
fetchResource(url, function (result) {
fetchResource(newUrl, function (result) {
fetchResource(anotherUrl, function (result) {
...
}, failureCallback);
}, failureCallback);
}, failureCallback);
try {
await fetchResource(url);
await fetchResource(newUrl);
await fetchResource(anotherUrl);
} catch (e) {
failureCallback(e);
}
new Promise((resolve, reject) => resolve('Hello'))
Is same as:
async () => 'Hello'
Is same as:
async function () { return 'Hello'; }
Second and third options can not be used in all cases as sometimes we need to handle events or callbacks
new Promise(
(resolve, reject) => setTimeout(() => resolve('Hello'), 1000)
)
promise
.then(result => {
console.log(result); // Operation succeeded
})
.catch(error => {
console.error(error); // Operation failed
})
.finally(result => {
console.error(result); // always executed
});
new Promise((resolve) => resolve('Labas'))
.then(result => result + ' ')
.then(result => result + 'Orbio')
.then(result => result + '!')
.then(result => console.log(result))
.catch(error => console.error(error));
Console Output?
Labas Orbio!
fetch('https://api.ipify.org?format=json')
.then(result => result.json()) // Operation succeeded
.then(result => {
console.log(result); // Operation succeeded
})
.catch(error => {
console.error(error); // Operation failed
});
try {
let response = await fetch('https://api.ipify.org?format=json')
let json = await response.json();
console.log(json);
} catch (error) {
console.error(error);
}
Same as
fetch('https://api.ipify.org?format=json')
.then(result => result.json()) // Operation succeeded
.then(result => {
console.log(result); // Operation succeeded
})
.catch(error => {
console.error(error); // Operation failed
});
new Promise((resolve) => resolve('Labas'))
.then(result => throw 'a')
// same as
.then(result => new Promise((resolve, reject) => reject('a'))
.catch(error => console.error(error));
new Promise(
(resolve, reject) => reject('some error')
)
.then(result => {
console.log('success:', result);
})
.catch(error => {
console.error('error:', error);
})
Log output?
error: some error
new Promise((resolve, reject) => reject('some error'))
.catch(error => {
console.error('error:', error);
})
.then(result => {
console.log('success:', result);
});
Log output?
error: some error success: undefined
new Promise((resolve, reject) => reject('some error'))
.then(result => {
console.log('success:', result);
})
.catch(error => {
console.error('error:', error);
})
new Promise((resolve, reject) => reject('some error'))
.catch(error => {
console.error('error:', error);
throw error;
})
.then(result => {
console.log('success:', result);
})
Task 1: https://jsfiddle.net/v1pakoLc/
Task 2: https://jsfiddle.net/v1pakoLc/2/
Task 3: https://jsfiddle.net/v1pakoLc/4/
Get slides from klimas.lt/slides