async await loop array push

김듑듑·2022년 9월 27일
0

프론트엔드

목록 보기
12/24

for문안에서 async await를 돌리고 push를 하려는 대환장의 상황이었음

const template: IScene[] = [];

for (const scn of scns) {
	const scene: IScene = {어쩌고저쩌고};
    
    const preview = (await editor.renderer.render(scene)) as string;
    template.push({ ...scene, preview });
}

근데 반복문 밖에선 array가 []로 읽히는거임
스택오버플로우 뒤져서 모든걸 실행해봄
결과물 2페이지 마지막에서 이걸 발견함

https://stackoverflow.com/questions/71995109/array-push-is-not-updated-inside-a-loop-in-node-js

exports.bulkCartUpdate = async (req, res) => {

  let userId = req.params.userId;
  let CartId = req.profile.CartId;
  let items = req.body;

  var promises = [];
  for (let i of items) {
    const productId = i.productId;
    const quantity = i.quantity;
    promises.push(Product.findById(productId).lean());
  }

  Promise.all(promises).then(async (products) => {
    // console.log(products);
  }).catch(e => console.error(e))
}

그래서 이렇게 수정완
await Promise.all(
      scns.map(async (scn) => {
        const scene: IScene = {어쩌고저쩌고};
        
        const preview = (await editor.renderer.render(scene)) as string;
        await template.push({ ...scene, preview });
      })
    );

근데 원래 1, 2, 3 순으로 push 되야하는데
다시 실행하면 2, 1, 3 뒤쥭박쮹 되는거임


왜냐...promise all은 비동기로 실행되어 완료순서를 보장받을 수 없기 때뮨에....힝규

그래서 for await of를 씀
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for-await...of

for await (const scn of scns) {
	const scene: IScene = {어쩌고저쩌고};
    
    const preview = (await editor.renderer.render(scene)) as string;
    await template.push({ ...scene, preview });
}

0개의 댓글