source

비동기 화살표 함수의 구문

bestscript 2023. 1. 6. 19:50

비동기 화살표 함수의 구문

자바스크립트 함수를 비동기(즉, 약속을 반환)로 마크할 수 있습니다.async키워드를 지정합니다.다음과 같이 합니다.

async function foo() {
  // Do something
}

화살표 함수와 동등한 구문은 무엇입니까?

비동기 화살표 함수는 다음과 같습니다.

const foo = async () => {
  // do something
}

비동기 화살표 함수는 단일 인수에 대해 다음과 같습니다.

const foo = async evt => {
  // do something with evt
}

비동기 화살표 함수는 여러 인수에 대해 다음과 같습니다.

const foo = async (evt, callback) => {
  // do something with evt
  // return response with callback
}

익명 폼도 기능합니다.

const foo = async function() {
  // do something
}

비동기 함수 선언은 다음과 같습니다.

async function foo() {
  // do something
}

콜백에서의 비동기 함수 사용:

const foo = event.onCall(async () => {
  // do something
})

클래스 내에서 비동기 메서드 사용:

async foo() {
  // do something
}

이 방법은 가장 간단한 방법으로async지정된 변수에 대한 화살표 함수 표현식:

const foo = async () => {
  // do something
}

(이는 엄밀하게는 동일하지 않습니다).async function foo() { }키워드와 화살표 표현의 차이 외에, 이 답변의 함수는 「맨 위로 이동」하지 않습니다).

즉시 호출된 비동기 화살표 함수:

(async () => {
    console.log(await asyncFunction());
})();

즉시 호출된 비동기 함수식:

(async function () {
    console.log(await asyncFunction());
})();

파라미터가 있는 비동기 애로우 함수 구문

const myFunction = async (a, b, c) => {
   // Code here
}

기본적인 예

folder = async () => {
    let fold = await getFold();
    //await localStorage.save('folder');
    return fold;
  };
async function foo() {
  // do something
}

다음과 같습니다.

const foo = async () => {
   // do something
}

다음 예시와 같이 하나의 인수를 사용하여 foo를 호출합니다.

async function foo(arg1) {
  // do something
}

이와 같이 foo를 호출하는 것과 동일합니다(괄호는 옵션이지만 인수가1개만 지정되어 있는 경우, 양쪽 모두 필요 없습니다).

const foo = async arg1 => {
  // do something
}

const foo = async (arg1) => {
  // do something
}

두 개 이상의 인수를 사용하여 foo를 호출하는 경우

async function foo(arg1, arg2) {
  // do something
}

동등: (부모님이 필요하게 되었습니다.

 const foo = async (arg1, arg2) => {
    // do something
 }

또한 내부가 대기용으로 사용되는 실제적인 예:

const foo = async () => await Promise.resolve('done');

다음 작업도 가능합니다.

 YourAsyncFunctionName = async (value) => {

    /* Code goes here */

}

비동기 함수

const getAllRedis = async (key) => {
  let obj = [];

  await client.hgetall(key, (err, object) => {
    console.log(object);
    _.map(object, (ob)=>{
      obj.push(JSON.parse(ob));
    })
    return obj;
    // res.send(obj);
});
}

정적 비동기 화살표 함수의 경우 다음과 같이 동작합니다.

static myFunction = async () => {
    // your code here
}

가장 간단한 방법

   const MyFunction = async ()=>{
      // do something here
   }
const asynchronousFunction = async () => {
  // do something;
  // await something else;
}

언급URL : https://stackoverflow.com/questions/42964102/syntax-for-an-async-arrow-function