[NODEJS]비동기함수처리Asynchronous function processing,PROMISE

일반적으로 동기라는 의미는 동시에 동작한다는 뜻이 있습니다.
반대로 비동기라는 의미는 동시에 동작하지 않는다는 뜻이 있습니다.
자바스크립트에서 동기라는 의미는 순차적인 실행을 의미합니다.
반대로 자바스크립트에서 비동기는 순차적인 실행이 아님을 의미합니다.

In general, synchronous means operating simultaneously.
Conversely, asynchronous means that they do not operate simultaneously.
In JavaScript, synchronous means sequential execution.
Conversely, in JavaScript, asynchronous means non-sequential execution.

1.비동기처리가 필요한 이유 Why asynchronous processing is necessary

기본적으로 자바스크립트의 함수는 처리 속도가 느린 함수는 나중에 실행됩니다.
그래서 자바스크립트의 함수는 비동기적입니다.
프로그램이 비동기적이면 실행 속도가 빠릅니다.
하지만 로그인이 되지 않으면 서비스를 이용할 수 없는 웹사이트처럼
느려도 로그인 과정이 반드시 선행 되어야 하는 경우가 있습니다.
이처럼 함수의 순차적인 사용에 필요한 것이 async function와 promise라고 생각하시면 됩니다.

By default, JavaScript functions that are slow to process are executed later.
So functions in JavaScript are asynchronous.
If a program is asynchronous, it runs faster.However, like a website where you cannot use the service unless you log in,
There are times when the login process must take precedence, even if it is slow.
Like this, promises and async functions are necessary for sequential use of functions.

이전에 다뤘던 call back function으로 함수의 순차적인 실행이 가능하지만
프로그램이 커질 수록 이해하기 어려운 코드가 됩니다.(call back hell이라고 부릅니다.)
이것을 개선하기 위해서 async function과 promise를 사용합니다.(promise hell도 있습니다.)

It is possible to execute functions sequentially with the previously discussed call back function, but
As the program grows, the code becomes more difficult to understand.(It’s called call back hell)
To improve this, use async functions and promises. (There is also promise hell.)

2.delay 함수(delay function)

Promise를 return하고 있습니다.아규먼트 ‘ms’는 밀레세컨드 값입니다.
setTimeout()함수는 ‘ms’밀리세컨드라는 시간이 지나면 작업을 실행 하는 함수 입니다.
이 함수는 비동기적인 작업이 될 수밖에 없는 함수 입니다.

It is returning a Promise. The argument ‘ms’ is the millisecond value.
The setTimeout() function is a function that executes a task after a period of ‘ms’ milliseconds.
This function has no choice but to operate asynchronously.

function delay(ms) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(`${ms} milliseconds.`);
      resolve();
    }, ms);
  });
}

3. async function/await

await키워드는 function앞에 async라는 키워드가 있는 함수 내에서만 사용 할 수 있습니다.
await키워드가 지정되면 작업이 완료되기까지 다음 작업으로 진행되지 않습니다.
await delay(1000);은 delay(1000);의 작업이 끝나고 나서 다음 작업으로 진행하라는 의미 입니다.
const result = await Promise.resolve(‘end’);는 promise의 return값으로 end 값을 result변수에 할당 합니다.

The await keyword can only be used within a function that has the async keyword in front of the function.
If the await keyword is specified, the next task will not proceed until the task is completed.
await delay(1000); means to proceed to the next task after the task of delay(1000); is completed.
const result = await Promise.resolve(‘end’); assigns the end value as the return value of the promise to the result variable

async function main() {
  console.log(0);       //1
  await delay(1000);    //await 2

  console.log(1);       //3
  console.log(2);       //4
  
  await delay(2000);    //await 5
  
  console.log(3);       //6
  const result = await Promise.resolve('end');
  
  console.log(4);      //7
  console.log(result); //8
  console.log(5);      //9
}

main();

4.function mainse()

일반적인 자바스크립트 함수입니다.
delay()함수가 가장 나중에 실행되는 것을 볼 수 있습니다.
delay()함수가 비동기적으로 실행된다는 의미 입니다.

This is a common JavaScript function.
You can see that the delay() function is executed last.
This means that the delay() function is executed asynchronously.

//return promise
// create delay function/ return Promise
function delay(ms) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(`${ms} milliseconds.`);
      resolve();
    }, ms);
  });
}

// async/await
async function main() {
  console.log(0);       //1
  await delay(1000);    //await 2

  console.log(1);       //3
  console.log(2);       //4
  
  await delay(2000);    //await 5
  
  console.log(3);       //6
  const result = await Promise.resolve('end');
  
  console.log(4);      //7
  console.log(result); //8
  console.log(5);      //9
}

main();


/*
// default 
function mainse(){
  console.log(0);       //0
  delay(1000);          //7

  console.log(1);       //1
  console.log(2);       //2
  
  delay(2000);          //8
  
  console.log(3);       //3
  const result = 'end'; //8
  console.log(4);       //4
  console.log(result);  //5
  console.log(5);       //6
}
mainse();
*/

Leave a Reply

Your email address will not be published. Required fields are marked *