[JS] Javascript #11 Summary
3 minute read
Javascript #11 Summary
promise
- promise is a JavaScript object for asynchronous operation.
- when new Promise is created, the executor runs automatically.
- 정해진 장시간의 기능을 수행하고나서
정상적으로 기능을 수행했다면 성공의 메세지와 함께 처리된 결과값 전달 (with resolve
),
만약 예상치 못한 문제가 발생했다면 Error 를 전달 (with reject
).
- producer: promise object, consumers: [
then
, catch
, finally
]
then
을 통해 값을 바로 전달하거나, promise object 를 전달한다.
- state: pending --> fulfilled (with
then
) or rejected (with catch
)
producer vs consumers
// 1. Producer (promise object)
const promise = new Promise((resolve, reject) => {
// doing some heavy work (network, read files)
console.log('doing something...');
setTimeout(() => {
// resolve('bruce');
reject(new Error('no network'));
}, 2000);
})
// 2. Consumers: then, catch, finally
promise
.then(value => { // return promise object
console.log(value);
})
.catch(error => {
console.log(error);
})
.finally(() => { // 성공 실패 상관없이 호출
console.log('finally');
});
promise chaining
const fetchNumber = new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000);
})
fetchNumber
.then(num => num * 2) // 1 * 2 = 2
.then(num => num * 3) // 2 * 3 = 6
.then(num => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num-1), 1000);
});
})
.then(num => conosole.log(num)); // 5
promise example
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('🐓'), 1000);
});
const getEgg = hen =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${hen} => 🥚`), 1000);
});
const cook = egg =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${egg} => 🍳`), 1000);
});
getHen()
.then(getEgg) // .then(hen => getEgg(hen))
.then(cook) // .then(egg => cook(egg))
.then(console.log); // .then(meal => console.log(meal));
Error Handling Example
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('🐓'), 1000);
});
const getEgg = hen =>
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(`${hen} => 🥚`), 1000));
});
const cook = egg =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${egg} => 🍳`), 1000);
});
getHen()
.then(getEgg)
.catch(error => {
return '🥖';
})
.then(cook)
.then(console.log)
.catch(console.log);
Callback chain to promise
Callback chain
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(() => {
if (
(id === 'bruce' && password === 'dev') ||
(id === 'bruce2' && password === 'dev2')
) {
onSuccess(id);
} else {
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === 'bruce') {
onSuccess({name: 'bruce', role: 'admin'});
} else {
onError(new Error('no access'));
}
}, 1000);
}
}
const userStorage = new UserStorage();
const id = prompt('Enter your id');
const password = prompt('Enter your password');
userStorage.loginUser(
id,
password,
(user) => {
userStorage.getRoles(
user,
userWithRole => {
alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role.`);
},
error => {
console.log(error);
},
);
},
error => {
console.log(error);
}
);
to promise
class UserStorage {
loginUser(id, password) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (
(id === 'bruce' && password === 'dev') ||
(id === 'bruce2' && password === 'dev2')
) {
resolve(id);
} else {
reject(new Error('not found'));
}
}, 2000);
});
}
getRoles(user) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (user === 'bruce') {
resolve({name: 'bruce', role: 'admin'});
} else {
reject(new Error('no access'));
}
}, 1000);
});
}
}
const userStorage = new UserStorage();
const id = prompt('Enter your id');
const password = prompt('Enter your password');
userStorage.loginUser(id, password)
.then(userStorage.getRoles)
.then(user => alert(`Hello ${user.name}, you have a ${user.role} role.`))
.catch(console.log);
Leave a comment