Array.map에서 비동기 대기 사용
다음 코드가 지정됩니다.
var arr = [1,2,3,4,5];
var results: number[] = await arr.map(async (item): Promise<number> => {
await callAsynchronousOperation(item);
return item + 1;
});
그러면 다음 오류가 발생합니다.
TS2322: 유형 'Promise<number>[]'는 유형 'number[]'에 할당할 수 없습니다.'Promise < number >'는 'number' 유형에 할당할 수 없습니다.
어떻게 하면 고칠 수 있죠?어떻게 하면async await
그리고.Array.map
함께 일합니까?
여기서의 문제는 당신이 이 문제를 해결하려고 한다는 것이다.await
'약속'이 아니라 '약속'의 배열입니다.이건 네가 기대한 대로 되지 않아.
오브젝트가 에 전달되었을 때await
약속은 아니지만await
는 해결하려고 하지 않고 있는 그대로의 값을 즉시 반환합니다.그래서 네가 합격했으니까await
여기서 Promise 대신 (Promise 객체의) 배열, wait에 의해 반환되는 값은 단순히 유형인 배열입니다.Promise<number>[]
.
당신이 하고 싶은 일은 아마도 전화하는 것이다.Promise.all
에 의해 반환된 어레이에map
이전에 단일 Promise로 변환하기 위해await
먹어버려요.
의 MDN 문서에 따르면:
그
Promise.all(iterable)
method는 반복 가능한 인수의 모든 약속이 해결되었을 때 해결되는 약속을 반환하거나 거부한 첫 번째 통과된 약속의 이유로 거부합니다.
고객님의 경우:
var arr = [1, 2, 3, 4, 5];
var results: number[] = await Promise.all(arr.map(async (item): Promise<number> => {
await callAsynchronousOperation(item);
return item + 1;
}));
그러면 여기서 발생한 특정 오류가 해결됩니다.
실행하려는 작업에 따라, 또는 를 사용하는 것도 고려할 수 있습니다.Promise.all
단, 대부분의 경우(이것을 포함해 거의 확실히)Promise.all
네가 원하는 사람이 될 거야
비동기 wait와 Array.map을 적절히 사용하기 위한 솔루션은 다음과 같습니다.어레이의 모든 요소를 병렬, 비동기적으로 처리하고 순서를 유지합니다.
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const randomDelay = () => new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
const calc = async n => {
await randomDelay();
return n * 2;
};
const asyncFunc = async() => {
const unresolvedPromises = arr.map(calc);
const results = await Promise.all(unresolvedPromises);
document.write(results)
};
document.write('calculating...')
asyncFunc();
코드펜도 있어요.
우리는 Promise.all만을 기다리고 있습니다."기다리지 않고 계산"을 여러 번 호출하고 해결되지 않은 약속들을 즉시 수집합니다.그럼 약속해.all은 모든 값이 확인되기를 기다렸다가 해결된 값이 순서대로 포함된 배열을 반환합니다.
네이티브 Promise가 아닌 Bluebird를 사용하고 있다면 다른 솔루션이 있습니다.
Promise.map()을 사용하여 array.map과 Promise를 혼재시킬 수도 있습니다.모든.
고객님의 경우:
var arr = [1,2,3,4,5];
var results: number[] = await Promise.map(arr, async (item): Promise<number> => {
await callAsynchronousOperation(item);
return item + 1;
});
이것이 그것을 하는 가장 간단한 방법이다.
await Promise.all(
arr.map(async (element) => {
....
})
)
Promise 배열에 매핑하면 모든 Promise를 숫자 배열로 해결할 수 있습니다.「Promise」를 참조해 주세요.모든 것.
다음을 사용할 수 있습니다.
for await (let resolvedPromise of arrayOfPromises) {
console.log(resolvedPromise)
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await.../
「 」를 사용하고 Promise.all()
'어울리다'로 하면 요.Promise.allSettled()
그래서 당신은 거절당한 약속을 더 잘 통제할 수 있다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
Promise 사용을 추천합니다.모두 상기와 같습니다만, 정말로 그 어프로치를 피하고 싶은 경우는, for 또는 그 외의 루프를 실행할 수 있습니다.
const arr = [1,2,3,4,5];
let resultingArr = [];
for (let i in arr){
await callAsynchronousOperation(i);
resultingArr.push(i + 1)
}
참고: 인덱스(@ralfoide의 코멘트)가 아닌 배열 항목에 대해 반복하려면 다음을 사용하십시오.of
in
에 inside inside inside let i in arr
★★★★★★ 。
modern-async의 map()을 사용한 솔루션:
import { map } from 'modern-async'
...
const result = await map(myArray, async (v) => {
...
})
이 라이브러리를 사용하면 mapLimit() 또는 mapSeries()를 사용하여 동시성을 제어할 수 있다는 장점이 있습니다.
Repo에서 모든 엔티티를 찾아 새 속성 URL을 추가하고 컨트롤러 계층으로 돌아가는 작업이 BE 측에서 수행되었습니다.(Ajedi32의 답변 덕분에) 이렇게 할 수 있었습니다.
async findAll(): Promise<ImageResponse[]> {
const images = await this.imageRepository.find(); // This is an array of type Image (DB entity)
const host = this.request.get('host');
const mappedImages = await Promise.all(images.map(image => ({...image, url: `http://${host}/images/${image.id}`}))); // This is an array of type Object
return plainToClass(ImageResponse, mappedImages); // Result is an array of type ImageResponse
}
주의: 이미지(엔티티)에는 속성 URL이 없지만 ImageResponse에는 속성 URL이 있습니다.
이게 도움이 될 수도 있어
const APISimulator = (v) => new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ data: v });
}, v * 100);
});
const arr = [7, 6, 5, 1, 2, 3];
const res = () => arr.reduce(async (memo, v, i) => {
const results = await memo;
console.log(`proccessing item-${i + 1} :`, v)
await APISimulator(v);
console.log(`completed proccessing-${i + 1} :`, v)
return [...results, v];
}, []);
res().then(proccessed => console.log(proccessed))
언급URL : https://stackoverflow.com/questions/40140149/use-async-await-with-array-map
'programing' 카테고리의 다른 글
표시되는 모든 마커를 포함하도록 지도 확대/축소 설정 (0) | 2022.10.14 |
---|---|
메모리 문제로 인해 MariaDB가 하루에 한 번 크래시됨 - 메모리를 더 할당해도 수정되지 않음 (0) | 2022.10.14 |
mysql - alter table modify 열은 행을 삭제할 수 없습니다. (0) | 2022.10.14 |
MySQL 설치: 오류: GEM 네이티브 확장을 빌드하지 못했습니다. (0) | 2022.10.05 |
python datetime을 읽을 수 있는 형식의 날짜를 가진 문자열로 변환하려면 어떻게 해야 합니까? (0) | 2022.10.05 |