for await of를 사용하면 Eslint에 의해 욕을 먹기 때문에 Promise.all 사용()

4382 단어 TypeScriptESLinttech

개시하다


TypeScript + Eslint 개발 for await of 에서 순환에서 비동기 함수를 동기화하려고 했을 때 Eslint에게 욕을 먹었다.
그때의 해결 방법으로 Promise.all() 해결 방법을 소개합니다.[1]

수정


해결책은 내가 추측을 했기 때문에 부적합하다고 판명했기 때문에 수정했다.
엄밀히 말하면, Eslint는 매우 화가 난다.
다음 설명에서는 마치 Promise.all()가 동기화 처리를 한 것처럼 보이지만 Promise.all() 어떤 문서에서도 동기화 처리를 설명하지 않았다.m(_ _)m

전제 조건


정의된 함수는 다음과 같습니다.
functions.ts
async function createUser(userId: number, userName: string) {
    ︙
    ︙
}

async function deleteUser(userId: number) {
    ︙
    ︙
}

욕먹다


hogehoge.ts
// 同時に複数のユーザを同期的に作りたいとする
const USER_DATA_LIST = [
    { userId: 1, userName: "User1" }
    { userId: 2, userName: "User2" }
    { userId: 3, userName: "User3" }
    { userId: 4, userName: "User4" }
    { userId: 5, userName: "User5" }
]

for await (const userData of USER_DATA_LIST) {
    await createUser(userData.userId, userData.userName)
}
https://eslint.org/docs/rules/no-await-in-loop
순환 내에 워낙 await를 사용할 수 없어서 욕을 먹을 거예요.

해결책


아래와 같이 이렇게 기술하면 욕을 먹지 않을 것이다.

Promise.all


fugafuga.ts

// 同時に複数のユーザを同期的に作りたいとする
const USER_DATA_LIST = [
    { userId: 1, userName: "User1" }
    { userId: 2, userName: "User2" }
    { userId: 3, userName: "User3" }
    { userId: 4, userName: "User4" }
    { userId: 5, userName: "User5" }
]

Promise.all(
    USER_DATA_LIST.map(userData => createUser(userData.userId, userData.userName))
)
Promise.all() 비동기 함수의 배열을 받아들인다(실제 상황은 반환 과정 중의 함수 등의 배열이다).따라서 맵 데이터 원본을 배열하는 동시에 비동기 함수를 되돌려줌으로써 비동기 처리를 스마트하게 반복할 수 있다.동기화 처리가 아닙니다.
스프레드시트 구조에서 스프레드시트로 변환하는 것을 잊지 마세요.[2]

적용 편(잘못된 기술에서 삭제)

Promise.all에 비슷한 거래를 하고 싶다고 기술했지만 위에서 말한 바와 같이 동기집행이 아닌 비동기집행이기 때문에 거래 같은 기술을 간단하게 쓸 수 없다.

외국 편


Promise.allSettled


중간 함수 중 하나가 실패하더라도 나머지 함수를 실행하려면 Promise.allSettled()를 사용합니다.
우리의 방법은 모든 함수의 집행이 끝난 후에 결과를 판정하는 것이다.
fugahoge.ts

// 同時に複数のユーザを同期的に作りたいとする
const USER_DATA_LIST = [
    { userId: 1, userName: "User1" }
    { userId: 2, userName: "User2" }
    { userId: 3, userName: "User3" }
    { userId: 4, userName: "User4" }
    { userId: 5, userName: "User5" }
]

Promise.allSettled(
    USER_DATA_LIST.map(userData => createUser(userData.userId, userData.userName))
)
    .then(results => {
        console.log(results) // すべての関数から返された結果の配列
    })
    // errorはThrowされず、resultsの中で、エラー理由等が確認できる。

Promise.race


위에서 소개한 방법은 모두 동기 집행 함수이지만 다른 단계로 총결하여 집행할 수도 있다.Promise.race() 가장 먼저 완성된 함수의 결과를 되돌려줍니다.
용도는 단번에 떠오르지 않지만 기억하면 어딘가에 쓸모가 있을지도 모른다.
fugehoga.ts

// 同時に複数のユーザを同期的に作りたいとする
const USER_DATA_LIST = [
    { userId: 1, userName: "User1" }
    { userId: 2, userName: "User2" }
    { userId: 3, userName: "User3" }
    { userId: 4, userName: "User4" }
    { userId: 5, userName: "User5" }
]

Promise.race(
    USER_DATA_LIST.map(userData => createUser(userData.userId, userData.userName))
)
    .then(result => {
        console.log(result) // 最も早く終わった関数の結果が返ってくる
    })
    .catch(error => {
	console.log(error) // 最も早くエラーがthrowされた関数のエラーが返ってくる
    })

총결산


이번에 Promise.all()와 관련Promise.allSettledPromise.race를 소개했다.
코디에 꼭 적용해서 예쁜 코드를 써 보세요.
끝까지 읽어주셔서 감사합니다.
각주
petamoriken 지적하고 정정해 주십시오.↩︎
petamoriken씨가 지적하고 삭제했습니다.↩︎

좋은 웹페이지 즐겨찾기