地獄
11775 ワード
'use strict'
// Javascript is synchronous!
// Execute the code block by order after hoisting
// hoisting : var, function declaration
// 자바스크립트 엔진은 모든 변수와 함수의 선언블록을 가장 위로 올린다음,
// 순차적으로 코드를 해석한다.
console.log(1)
// browser's api
setTimeout(()=>console.log(2),1000) // 브라우저에게 요청
console.log(3)
// Synchronous callback
function printImmediately(print){
print()
}
printImmediately(()=>console.log('hello!'))
// Asynchronous callback
function printWithDelay(print, timeout){
setTimeout(print, timeout)
}
printWithDelay(()=>console.log('this is async callback'), 2000) // 브라우저에게 요청
// Callback Hell example
// 백엔드(서버)에서 사용자의 데이터를 받아오는 클래스
// 두가지의 api가 있다고 가정
class UserStorage{
loginUser(id, password, onSuccess, onError){
setTimeout(()=>{
if ((id === 'ellie' && password === 'dream') ||
(id === 'coder' && password === 'academy')
){
onSuccess(id);
}else{
onError(new Error('not found...'))
}
}, 2000)
}
getRoles(user, onSuccess, onError){
setTimeout(()=>{
if (user === 'ellie'){
onSuccess({name:'ellie', role:'admin'});
}else{
onError(new Error('no access...'))
}
},1000)
}
}
const userStorage = new UserStorage();
const id = prompt('please enter your id')
const password = prompt('please enter your password')
userStorage.loginUser(id, password, (user) =>{
userStorage.getRoles(user, userWithRole=>{
alert(`Hello ${userWithRole.name}, you hava a ${userWithRole.role}`)
}, error =>{})
}, (error)=>{console.log(error)})
Reference
この問題について(地獄), 我々は、より多くの情報をここで見つけました https://velog.io/@yeonnex/콜백지옥テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol