컴퓨터/nodejs

callback 함수의 이해, 한글인코딩, 변수, API서버만들기, promise, async, await

풍경소리^^ 2022. 12. 15. 08:59

https://www.youtube.com/watch?v=Tt_tKhhhJqY 

JSON 26:00

한글인코딩 37:07

변수 40:00

API서버만들기 45:48

 

생활코딩 JavaScript - callback

https://www.youtube.com/watch?v=TAyLeIj1hMc&list=PLuHgQVnccGMBVQ4ZcIRmcOeu8uktUAbxI 

callback

function fn() {
  val = function(양) {
    return 말
    }
  return val;
}
val = function(양){ // 일반 함수이지만
		 return 말
      }
      
function fn(arg){
	arg();
}

fn(val) // 다른 함수fn에 의해서 호출된다 - callback 함수
words = ['a','b','c','d','e'];
// newWords = words.filter(element=>element.length>6);
function myfilter(origin, callback){
	var result = [];
    for (var i=0; i<origin.lenth; i++){
    	var current = origin[i];
        if (callback(current)){
        	result.push(current);
        }
    }
    return result;
}
newWords = myfilter(words, elemnt=>element.length > 6);
console.log(newWords);

https://www.youtube.com/watch?v=s1vpVCrT8f4&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=11 

callback.js--------------------

'use strict';

// JavaScript is synchronous.
// Execute the code block by order after hoisting.
// hoisting: var, function declaration

console.log('1');
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('async callback'), 2000);

node callback.js

1

3

hello

2

async callback

// 우리가 원하는 것은 1 2 3 으로 하고 싶다

callback1.js--------------------

'use strict';

// JavaScript is synchronous.
// Execute the code block by order after hoisting.
// hoisting: var, function declaration

console.log('1'); // 순서1
setTimeout(() => { // 호이스팅 // 큐1
  console.log('2') // 순서3
  setTimeout(() => { // 큐3
    console.log('3'); // 순서5
  }, 1000)
}, 1000);

// Synchronous callback
function printImmediately(print) { // 호이스팅
  print();
}

printImmediately(() => console.log('hello')); // 순서2

// Asynchronous callback
function printWithDelay(print, timeout) { // 호이스팅
  setTimeout(print, timeout);
}

printWithDelay(() => console.log('async callback'), 2000); // 큐2 // 순서4

node callback1.js

1
hello
2
async callback
3

 

callbackhell.js--------------------

'use strict';
// npm install prompt-sync
const prompt = require("prompt-sync")();

// Callback Hell example
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('enter your id : ');
const password = prompt('enter your password : ');
userStorage.loginUser(
  id,
  password,
  loginUser_onSuccess_id => {
    userStorage.getRoles(
      loginUser_onSuccess_id,
      getRoles_onSuccess_user => {
        // alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`);
        console.log(`\n====================\nHello ${getRoles_onSuccess_user.name}, you have a ${getRoles_onSuccess_user.role} role\n====================`);
      },
      error => {
        console.log(error);
      }
    );
  },
  error =>{console.log(error)}
);

callbackhell1.js--------------------

'use strict';

// JavaScript is synchronous.
// Execute the code block by order after hoisting.
// hoisting: var, function declaration

console.log('1'); // 순서1
setTimeout(() => { // 호이스팅 // 큐1
  console.log('2') // 순서3
  setTimeout(() => { // 큐3
    console.log('3'); // 순서5
    setTimeout(() => { // 큐4
      console.log('4'); // 순서6
      setTimeout(() => { // 큐5
        console.log('5'); // 순서7
        setTimeout(() => { // 큐6
          console.log('6'); // 순서8
          setTimeout(() => { // 큐7
            console.log('7'); // 순서9
            setTimeout(() => { // 큐8
              console.log('8'); // 순서10
            }, 1000)
          }, 1000)
        }, 1000)
      }, 1000)
    }, 1000)
  }, 1000)
}, 1000);

// Synchronous callback
function printImmediately(print) { // 호이스팅
  print();
}

printImmediately(() => console.log('hello')); // 순서2

// Asynchronous callback
function printWithDelay(print, timeout) { // 호이스팅
  setTimeout(print, timeout);
}

printWithDelay(() => console.log('async callback'), 2000); // 큐2 // 순서4

node callbackhell1.js

1
hello
2
async callback
3
4
5
6
7
8

 

promise - 서버와의 통신 - 언제 가져오기가 끝날지 모르는 데이터에 대해서 비동기적으로 처리

console.log(1);
fetch('https://jsonplaceholder.typicode.com/posts')
	.then(function(response){
    	return response.json();
    })
    .then(function(myJson) {
    	console.log(myJson);
    });
console.log(2);

비동기적인 작업을 처리할 때, 

그 작업이 성공했는지, 실패했는지를

표준화된 방식으로 처리할 수 있게 해준다

성공시 then 으로 처리된 결과를 보여주고

실패시 chtch로 처리되어 그 이유를 보여준다

fetch('https://jsonplaceholder.typicode.com/posts');
	.then(function(response){
    	console.log('response', response);
    })
    .catch(function(reason){
    	console.log('reason', reason);
    });
fetch('https://jsonplaceholder.typicode.com/posts');
	.then(function(response){
    	// response.json().then(function(data){
    	//	console.log('response', response);
        // });
        return response.json();
    })
    .catch(function(reason){
    	console.log('reason', reason);
    });
    .then(funtion(data){
    	console.log('data', data);
    });
timer(1000, function(){
	console.log('작업1');
    timer(1000, function(){
    	console.log('작업2');
        timer(1000, function(){
        	console.log('작업');
        });
    });
});
timer(1000)
	.then(function(){
		console.log('작업1');
        return timer(1000);
    })
    .then(function(){
		console.log('작업2');
        return timer(1000);
    })
    .then(function(){
		console.log('작업3');
    })

promise.js--------------------

'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.
const promise = new Promise((resolve, reject) => {
  // doing some heavy work (network, read files)
  console.log('doing something 만들자마자 바로 실행...')
  setTimeout(() => {
    // resolve('ellie'); // 성공했을 때
    reject(new Error('no network')); // 실패했을 때
  }, 2000);
});

// 2. Consumers: then, catch, finally
promise
  .then(value => {
    console.log(value);
  }) // Promise는 Promise를 return하니까 .then .catch 처럼 체인닝이 가능해진다
  .catch(error => {
    console.log(error);
  })
  .finally(() => {
    console.log('finally');
  });

// 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(egg => cook(egg))
// .then(meal => console.log(meal));

// getHen().then(getEgg).then(cook).then(console.log);
// 코멘트 주석을 뒤에 붙이면

getHen() //
  .then(getEgg)
  .catch(error => {
    return '🍞';
  })
  .then(cook)
  .then(console.log)
  .catch(console.log);

 

sample22.js--------------------Promise

'use strict';

function workP(sec) {
  // Promise의 인스턴스를 반환하고
  // then에서 반환한 것을 받는다.
  return new Promise((resolve, reject) => {
    // Promise 생성시 넘기는 callback = resolve, reject
    // resolve 동작 완료시 호출, 오류 났을 경우 reject
    setTimeout(() => {
      resolve(new Date().toISOString());
    }, sec * 1000);
  });
}

workP(1).then((result) => {
  console.log('첫 번째 작업', result);
  return workP(1);
}).then((result) => {
  console.log('두 번째 작업', result);
});

node sample22.js

 

첫 번째 작업 2023-03-10T03:52:23.577Z
두 번째 작업 2023-03-10T03:52:24.600Z

 

Promise 사용시 then()을 붙인 순서대로 처리됩니다.

 

index.html--------------------

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=`, initial-scale=1.0">
  <title>Document</title>
  <script src="async/callback-to-promise.js" defer></script>
</head>
<body>
  
</body>
</html>

callback-to-promise.js--------------------

'use strict';
// npm install prompt-sync
const prompt = require("prompt-sync")();

// Callback Hell example
class UserStorage {
  loginUser(id, password) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (
          (id === 'ellie' && password === 'dream') ||
          (id === 'coder' && password === 'academy')
          ) {
            resolve(id);
          } else {
            reject(new Error('not found'));
          }
        }, 2000);
    });
  }

  getRoles(user) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (user === 'ellie') {
          resolve({ name: 'ellie', 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 => console.log(
  `\n====================\nHello ${user.name}, you have a ${user.role} role\n====================`))
.catch(console.log(`\n====================\nERROR\n====================`));

 

https://www.youtube.com/watch?v=znlg4YhOLro 

callbackhellpromise.js--------------------

'use strict';

// JavaScript is synchronous.
// Execute the code block by order after hoisting.
// hoisting: var, function declaration

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

p1
  .then((data) => {
    console.log(data);
    return data + 1
  })
  .then((data) => {
    console.log(data);
    return data + 1
  })
  .then((data) => {
    console.log(data);
    return data + 1
  })
  .then((data) => {
    console.log(data);
    return data + 1
  })
  .then((data) => {
    console.log(data);
    return data + 1
  })
  .then((data) => {
    console.log(data);
    return data + 1
  })
  .then((data) => {
    console.log(data);
    return data + 1
  })
  .then((data) => {
    console.log(data);
  })

node callbackhellpromise.js

 

1
2
3
4
5
6
7
8

 

await 은 다른 함수 안에 있어야 하고

그 함수의 앞에는 async 가 붙어있어야 한다

async function run() {
            await timer(1000)
                console.log('작업1')
            await timer(1000)
                console.log('작업2')
            await timer(1000)
                console.log('작업3')
    	}
    	run();

async.js--------------------

// async & await
// clear style of using promise

// 1. promise
// function fetchUserP() {
//   return new Promise((resolve, reject) => {
//     // do network reqeust i n 10 secs....
//     resolve('ellie');
//   });
// }

// const userP = fetchUserP();
// userP.then(console.log);
// console.log(userP);

// 2. async
// async function fetchUserA() { // 함수 앞에 async 쓰면 자동으로 Promise로 변환된다
//     return 'ellie';
// }

// const userA = fetchUserA();
// userA.then(console.log);
// console.log(userA);

// 3. await ✨Win + ;
function delay(ms) { // 함수 앞에 async 쓰면 자동으로 Promise로 변환된다
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function getApple() {
  await delay(1000); // await은 async가 앞에 붙은 함수 안에서만 사용할 수 있다
  return '🍎';
}
async function getBanana() {
  await delay(1000);
  return '🍌';
}
// function getBanana() {
//   return delay(3000)
//   .then(() => '🍌') ;
// }

function pickFruits() {
  return getApple().then(apple =>{
    return getBanana().then(banana => `${apple} + ${banana}`);
  });
}

pickFruits().then(console.log);

node async.js

 

🍎 + 🍌

 

sample23.js--------------------async/await

'use strict';

function workP(sec) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(new Date().toISOString());
    }, sec * 1000);
  });
}

function justFunc() {
  return 'just Function';
}

async function asyncFunc() {
  return 'async Function';
}

console.log(justFunc());
console.log(asyncFunc());
console.log(workP());

node sample24.js

 

just Function
Promise { 'async Function' }
Promise { <pending> }

 

sample23.js--------------------async/await

'use strict';

function workP(sec) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(new Date().toISOString());
    }, sec * 1000);
  });
}

function justFunc() {
  return 'just Function';
}

async function asyncFunc() {
  return 'async Function';
}

console.log(justFunc());
console.log(asyncFunc());
// console.log(workP());
workP(1).then((result) => {
  console.log(result);
});

 

node sample24.js

 

just Function
Promise { 'async Function' }
2023-03-10T05:25:44.440Z

 

sample24.js--------------------

'use strict';

function workP(sec) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('workP function');
    }, sec * 1000);
  });
}

async function asyncFunc() {
  const result_workP = await workP(1);
  console.log(result_workP);
  return 'async Function';
}

asyncFunc().then((result) => {
  console.log(result);
});

node sample24.js

 

workP function
async Function

 

https://www.youtube.com/watch?v=JzXjB6L99N4 

 

https://www.youtube.com/playlist?list=PLuBMRNcyzsWwidiVVMmD3YSh0oKTqW8sW 

 

자바스크립트 예외처리

자바스크립트의 예외처리에 대해 4개의 영상으로 나눠서 설명중입니다. 4번째 영상은 async/await 에서의 예외처리에 대해 다룰 예정이며 곧 공개 됩니다. 구독 / 좋아요 / 알림 설정 잊지마세요!

www.youtube.com

 

'컴퓨터 > nodejs' 카테고리의 다른 글

Node.js & MySQL 생활코딩  (0) 2023.03.23
Node.js server 코딩애플  (0) 2023.02.28
Node.js 백엔드맛보기1  (0) 2022.01.11
Node.js 다음메일 여러 개 보내기  (0) 2022.01.10
nodejs pm2 메모  (0) 2021.10.13