JS 반복문 안에서 api 호출하기

박경준·2021년 11월 26일
1

반복문 안에서 api를 호출하기는 정말 어려웠다;;...
api 호출이 다 될때까지 기다렸다가 반복문의 다음 스텝으로 넘어가지 않고 반복문은 막 넘어가기 때문...

핵심은 반복문 내 로직을 별도의 함수로 빼고,
await Promise.all으로 반복문을 감싸서 반복문 내 로직이 끝나야 반복문의 다음 세션으로 넘어가도록 해야함.

예시

const sendEmail = userEmail => {
  return new Promise(async (resolve, reject) => {
    //this is a mock email send logic
    setTimeout(() => {
      resolve(`Email Sent to ${userEmail}`)
    }, 3000)
  })
}

const sendEmails = async () => {
  const userEmails = ["ganesh@gmail.com", "john@gmail.com", "Sam@gmail.com"]
  const status = await Promise.all(userEmails.map(email => sendEmail(email)))
  console.log("Status =>", status)
}

적용

methods: {
  postDisclosure(file) {
    AWS.config.update({
      region: this.s3BucketRegion,
      credentials: new AWS.CognitoIdentityCredentials({
        IdentityPoolId: this.s3IdentityPoolId,
      }),
    });

    const fileSize = file.size,
          fileName = file.name,
          s3Key = `disclosure-pdf/${fileName}`,
          upload = new AWS.S3.ManagedUpload({
            params: {
              ContentLength: fileSize,
              Key: s3Key,
              Body: file,
              ACL: "public-read",
              Bucket: this.s3BucketName,
            },
          });
    return new Promise(async (resolve, reject) => {
      resolve(upload.promise() // 비동기 구문);
    });
  },

    async postDisclosures() {
      const data = await Promise.all(
        this.disclosures.map((disclosure) => {
          return this.postDisclosure(disclosure);
        })
      );
      return data;
    },
      async postProductDetails() {
        const data = await this.postDisclosures();
        const params = data.map((obj, idx) => {
          const disclosure = obj.Location
          const item = {
            saleStartDate: this.saleStartDates[idx],
            saleEndDate: this.saleEndDates[idx],
            productMasterId: this.masterProduct.id,
            disclosureUrl: disclosure,
          }
          return item;
        });
        console.log(params)
      },
}

3시간 안녕~

profile
빠굥

0개의 댓글