๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“’ JavaScript

javascript ๊ณผ Promise ์™€ async await

by Tamii 2021. 3. 15.
๋ฐ˜์‘ํ˜•

์›๋ณธ ์ฝ”๋“œ (callback ์ง€์˜ฅ์— ๋น ์งˆ๋ž‘ ๋ง๋ž‘)

url์˜ json ๋ฐ์ดํ„ฐ์™€ json ์ค‘ title ๋ฐ์ดํ„ฐ๋ฅผ ๋น„๋™๊ธฐ์ ์œผ๋กœ ์ถœ๋ ฅ์‹œํ‚ค๋Š” code

1์ดˆ ํ›„ json ์ถœ๋ ฅ

๊ทธ๋กœ๋ถ€ํ„ฐ 2์ดˆ ํ›„ json.title ์ถœ๋ ฅ

 

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then( (json)=> {
    setTimeout(() => {
      console.log(json);
      setTimeout( () => {
        console.log(json.title);
      },2000);
    },1000);
  })

 ์ฝœ๋ฐฑ ํ•จ์ˆ˜ ๋ถ„๋ฆฌ์™€ then ์‚ฌ์šฉ 

Promise๋ฅผ ์‚ฌ์šฉํ•ด๋ณด์ž

const delay = (data,ms) =>new Promise((resolve) => setTimeout(()=> resolve(data),ms));

 

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then((json)=> delay(json,1000))
  .then( json => { 
    console.log(json)
    return json;
  })
  .then( (json)=> delay(json,2000))
  .then( (result) => console.log(result.title)))

ํ•จ์ˆ˜์˜ ํ๋ฆ„์„ ํ•œ๋ˆˆ์— ํŒŒ์•… ๊ฐ€๋Šฅ 

 

 

 

async await 

์ดˆ๊ธฐ์ž‘(์‹คํŒจ)

(async function() {
    const res = await fecth('https://jsonplaceholder.typicode.com/todos/1')
const jsondata = await res.json();
console.log(delay(1000,jsondata));
console.log(delay(2000,jsondata.title))})();

async ํ•จ์ˆ˜๋ช… ์—†์Œ

delay ์ธ์ž ๊ฐ’ ์ˆœ์„œ ํ‹€๋ฆผ

 

async function run() {
    const res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
    
	const jsondata = await res.json();
	await delay('',1000);
	console.log(jsondata);
    
	await delay('',2000);
	return jsondata; 
 }

run().then((res)=>{ console.log(res.title);});

 

 

javascript ์—์„œ aysnc ์™€ await ์‚ฌ์šฉ ์‹œ ์ฃผ์˜ํ•  ์  

async fuction {
 await funcA();
 funcB();
 
}

funcA() ์™€ funcB()๊ฐ€ ์–ด๋–ค ์—ฐ๊ฒฐ๋„ ๋˜์–ด์žˆ์ง€ ์•Š๋‹ค๋ฉด 

funcB()๋Š” A๊ฐ€ ์ฒ˜๋ฆฌ๋  ๋•Œ๊นŒ์ง€ blocking ๋  ์ˆ˜๋„ ์žˆ์œผ๋ฏ€๋กœ ์ฃผ์˜

 

 

 

 


์ค‘์ฒฉ๋œ setTimeout -> await async ์ด์šฉํ•˜๊ธฐ

setTimeout(()=>{
	funcA()
    
    setTimeout(()=>{
    	funcB()
    },1000);
  
},2000);  

 

const delay = (data,ms) =>new Promise((resolve) => setTimeout(()=> resolve(data),ms));
await delay(1000);
funcA();

await delay(1000);
funcB();

 

 

์ค‘์ฒฉ๋œ setTimeout์€ callback ์ง€์˜ฅ์— ๋น ์ง€๊ธฐ ์‰ฝ๋‹ค.

์ฐจ๋ผ๋ฆฌ ๋‚˜๋งŒ์˜ delayํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด await/async ์ฒ˜๋ฆฌ๋ฅผ ํ•˜๋˜์ง€,

promise.then ๊ธฐ๋Šฅ์„ ์“ฐ๋Š”๊ฒŒ ๋‚˜์Œ

 

 

๋Œ“๊ธ€