일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- dataframe
- bulk post
- Jpype
- MariaDB
- centos8
- dead lock
- git bash
- KONLPY
- jvm.py
- pip install mariadb
- ELASTIC
- tweepy
- 나무자르기
- Pythonic
- pandas
- 백준
- js
- 완주하지못한선수
- ShallowCopy
- bs4
- pyLDAvis
- 토픽모델링
- 프로그래머스
- ChromeDriverManager
- Python.h
- 파이썬
- gensim
- elastic search
- Java
- rest api
- Today
- Total
부리부리부리
[JS] async/await/promise 본문
과제
async,await,promise,setTimeout를 이용하여
1초, 2초, 3초, 4초, 5초 간격으로 함수가 동작하도록 구현
JavaScript는 비동기적 언어이다. 모든 코드가 비동기적으로 돌아간단 것이 아니라
특정 상황(ex : 함수가 Web API 호출, setTimeout )에 코드가 비동기적으로 돌아간다는 얘기인데, 이를 동기적으로 처리할 수 있게 해주는 것들 중 하나가 Promise 객체와 async&await이다.
내가 배운 것에 한해서, async&await은 promise 객체를 인지해 동기적으로 구현해주는 기능을 한다.
다음은 처음 과제를 받았을 때 내가 짠 코드이다.
async function test(){
await setTimeout(()=>{
console.log('1000')
},1000)
await setTimeout(()=>{
console.log('2000')
},2000)
await setTimeout(()=>{
console.log('3000')
},3000)
await setTimeout(()=>{
console.log('4000')
},4000)
await setTimeout(()=>{
console.log('5000')
},5000)
}
test();
ㅋㅋ쉽네 하고 작동해보니.. 저 모든게 5초 안에 끝나더라..
분명 1초 후 '1000'이 찍히고 또 2초 후 '2000'이 찍히고.. 가 반복되어서 15초 후에 '5000'이 찍힐 줄 알았는데..
https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout
Combination of async function + await + setTimeout
I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working: async function asyncGenerator() { // other code ...
stackoverflow.com
늘 그렇듯 킹택오버플로우 형님들이 해결해주셨다..
요약하자면
setTimeout은 promise객체가 아니기에 async&await이 무용지물이 된 것이었다.
( async&await은 정말 promise 객체만 받아들이나?)
따라서 setTimeout을 promise 객체에 넣을 필요가 있었기에 코드를 수정했다.
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function test(){
await timeout(1000)
console.log("1")
await timeout(2000)
console.log("2")
await timeout(3000)
console.log("3")
await timeout(4000)
console.log("4")
await timeout(5000)
console.log("5")
}
test();
ㅅㄱ용 ^^
참고 사이트:
[Javascript] 비동기, Promise, async, await 확실하게 이해하기 – Under The Pencil
개요 본 글은 자바스크립트에서 Promise 에 대한 개념을 잡기 위해 작성한 글입니다. 자바스크립트의 기본 문법을 먼저 알아야 이 글을 조금 더 수월하게 보실 수 있습니다. 필자는 Node.js 기반에서
elvanov.com
- https://joshua1988.github.io/web-development/javascript/javascript-asynchronous-operation/
'언어 > JavaScript' 카테고리의 다른 글
[JS] 깊은 복사, 얕은 복사 (0) | 2021.12.21 |
---|