๋ฐ์ํ
์๋ณธ ์ฝ๋ (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 ๊ธฐ๋ฅ์ ์ฐ๋๊ฒ ๋์
'๐ JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS Tam9์ํ] #1 DOM (0) | 2021.07.16 |
---|---|
[JavaScript] Closure ๊ณผ Currying (0) | 2021.04.09 |
[Javascript] Prototype ์ ํตํ ์์ ๊ณผ __proto__ +(MDN ์์ ๋ก ๋ณด๋ Prototype ์์) (0) | 2021.03.12 |
[JavaScript ] prototype vs __proto__ + ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ (0) | 2021.03.11 |
[Javascript] __proto__ ์ ์์ (0) | 2021.03.11 |
๋๊ธ