전체 글 (166)

09
16

ex)

'use strict';

//Promise is a JavaScript object for asynchronous operation.
//state: pending -> fulfilled(성공) or rejected(오류)
//Producer vs Consumer

//1.Producer
//when new Promise is created, the executor runs automatically. promise를 만드는 순간 실행됨
const promise = new Promise((resolve, reject)=>{
    //doing some heavy work(network, read files)
    console.log('doing something...');
    setTimeout(()=>{
        resolve('han');
        //reject(new Error('no network'));
    },2000);
});

//2. Consumers: then, catch, finally
promise 
    .then(value =>{ //promise가 정상적으로 될 경우 resolve의 파라미터가 value로 들어옴
    console.log(value);
    })
    .catch(error => {//promise가 오류가 날경우 reject의 파라미터가 error 들어옴
        console.log(error);
    })
    .finally(()=>{
        console.log('finally');
    });

 

예제 실행 화면

 

ex)

//3. Promise chaining
const fetchNumber = new Promise((resolve,reject)=>{
    setTimeout(()=>resolve(1),1000);
});

fetchNumber //
    .then(num => num * 2)
    .then(num => num * 3)
    .then(num => {
        return new Promise((resolve, reject) =>{
            setTimeout(()=>resolve(num-1),1000);
        });
    })
    .then(num=>console.log(num));

//4. Error Handling
const getHen = () =>
    new Promise((resolve, reject) =>{
        setTimeout(()=>resolve('닭'),1000);
    });
const getEgg = hen =>
    new Promise((resolve, reject)=>{
        //setTimeout(()=>resolve(`${hen} => 달걀`),1000);
        setTimeout(()=>reject(new Error(`error! ${hen} => 달걀`)),1000);
    });
const cook = egg =>
    new Promise((resolve,reject)=>{
        setTimeout(()=>resolve(`${egg} => 요리`),1000);
    });

getHen() //
    .then(hen => getEgg(hen)) // .then(getEgg)
    .catch(error => {
        return '빵';
    })
    .then(egg => cook(egg))
    .then(meal => console.log(meal)) // .then(console.log);
    .catch(console.log);

 

예제 실행 화면

 

ex)

class UserStorage{
    loginUser(id, password){
        return new Promise((resolve, reject)=>{
            setTimeout(()=>{
                if(
                    (id==='han'&&password==='dream')||
                    (id==='jin'&&password==='academy')
                ){
                    resolve(id);
                }else{
                    reject(new Error('not found'));
                }
            },2000);
        });
    }

    getRoles(user){
        return new Promise((resolve, reject)=>{
            setTimeout(()=>{
                if(user==='han'){
                    resolve({name: 'han',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);

 

 

COMMENT
 
09
16

ex)

'use strict';

//JavaScript is synchronous.
//Execute the code block in order after hoisting.
//hoisting: var, function declaration
console.log('1');//동기
setTimeout(function(){
    console.log('0');
},1000);//비동기적인 실행방법(소스 순서에 맞지 않게 실행됨)
//setTimeout(()=>console.log('0'),1000);
console.log('2');//동기
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('async callback'), 2000);//비동기

 

예제 실행 화면

 

ex)

//Asynchronous callback
function printWithDelay(print, timeout){
    setTimeout(print,timeout);
}
printWithDelay(()=> console.log('async callback'), 2000);//비동기
console.clear();

//Callback Hell example
class UserStorage{
    loginUser(id,password,onSuccess,onError){
        setTimeout(()=>{
            if(
                (id==='han'&&password==='dream')||
                (id==='jin'&&password==='academy')
            ){
                onSuccess(id);
            }else{
                onError(new Error('not found'));
            }
        },2000);
    }
    
    getRoles(user,onSuccess,onError){
        setTimeout(()=>{
            if(user==='han'){
                onSuccess({name: 'han',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);
});

 

예제 실행 화면

 

 

COMMENT
 
09
16

ex)

//JSON
//Javascript Object Notation

//1.Object to JSON
//stringfy(obj)
let json = JSON.stringify(true);
console.log(json);

json = JSON.stringify(['apple','banana']);
console.log(json);

const rabbit ={
    name: 'tori',
    color: 'white',
    size: null,
    birthDate: new Date(),
    jump:() => {
        console.log(`${name} can jump!`);
    },
};
json = JSON.stringify(rabbit);
console.log(json);

json = JSON.stringify(rabbit, ['name','color']);
console.log(json);

json = JSON.stringify(rabbit, (key, value) => {
    console.log(`key: ${key}, value: ${value}`);
    return key === 'name' ? 'han' : value;
});
console.log(json);

 

예제 실행 화면

 

ex)

//2.JSON to Object
//parse(json)
json = JSON.stringify(rabbit);
const obj = JSON.parse(json);
console.log(obj);
rabbit.jump();
//obj.jump(); //에러

console.log(rabbit.birthDate.getDate());
//console.log(obj.birthDate.getDate()); // birthDate가 스트링이기 때문에 에러
console.log(obj.birthDate);

const obj2 = JSON.parse(json, (key,value)=>{
    console.log(`key: ${key}, value: ${value}`);
    return key === 'birthDate' ? new Date(value) : value;
});
console.log(obj2.birthDate.getDate());

 

예제 실행 화면

 

유용한 사이트

  • JSON Diff
  • JSON Beautifier
  • JSON Parser
  • JSON Validator

 

COMMENT
 
09
15

ex)

// Q1. make a string out of an array
{
    const fruits = ['apple', 'banana', 'orange'];
    const result = fruits.join('');
    console.log(result);
    const result = fruits.join(', and');
    console.log(result);
}

 

예제 실행 화면

 

ex)

// Q2. make an array out of a string
{
    const fruits = '🍎, 🥝, 🍌, 🍒';
    const result3 = fruits.split(',');
    console.log(result3);
    const result4 = fruits.split(',',2);
    console.log(result4);
}

 

예제 실행 화면

 

ex)

// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
    const array = [1, 2, 3, 4, 5];
    const result5 = array.reverse();
    console.log(result5);
    console.log(array);
}

 

예제 실행 화면

 

ex)

// Q4. make new array without the first two elements
{
    const array = [1, 2, 3, 4, 5];
    const result6 = array.slice(2, 5);
    console.log(result6);
    console.log(array);
}

 

예제 실행 화면

 

ex)

class Student {
constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
}
}
const students = [
new Student('A', 29, true, 45),
new Student('B', 28, false, 80),
new Student('C', 30, true, 90),
new Student('D', 40, false, 66),
new Student('E', 18, true, 88),
];

// Q5. find a student with the score 90
{
    const result7 = students.find((student) => student.score === 90);
    console.log(result7);
}

 

예제 실행 화면

 

ex)

// Q6. make an array of enrolled students
{
    const result8 = students.filter((stduenct) => stduenct.enrolled);
    console.log(result8);
}

 

예제 실행 화면

 

ex)

// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
{
    const result = students.map((student) => student.score);
    console.log(result);
}

 

예제 실행 화면

 

ex)

// Q8. check if there is a student with the score lower than 50
{
    const result = students.some((student)=>student.score < 50);
    console.log(result);
    const result2 = !students.every((student) => student.score >= 50);
    console.log(result2);
}

 

예제 실행 화면

 

ex)

// Q9. compute students' average score
{
    const result = students.reduce((prev, curr) => {
        return prev + curr.score}, 0) / students.length;
    console.log(result);
}
//reduceRight

 

예제 실행 화면

 

ex)

// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
{
    const result = students.map(student => student.score).join();
    console.log(result);
}

 

예제 실행 화면

 

ex)

// Bonus! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
{
    const result = students.map(student => student.score).sort().join();
    console.log(result);
}

 

예제 실행 화면

COMMENT