简体   繁体   中英

The array remains empty even if I send items to it and they appear in it VueJs

I'm facing a very strange problem that I can't figure out. So I want to retrieve some data from an api

getPaymentsLinkItems() {
            let items = [];
            this.paymentLinks.forEach(async (link) => {
                let object = {};
                let response = await this.stripe.get(`/payment_links/${link.id}/line_items`);
                items.push({[response.data.data[0].price.product]: link.url});
                object = {};
            });

            console.log(items);
        }

Even if I send those data in the array as you can see, they appear in it but the length is 0 and I can't access anything

[]
0: {prod_MI6m3mRfVAG6b: 'https://buy.stripe.com/'}
1: {prod_MI6IMPKoUoo1I: 'https://buy.stripe.com/'}
length: 2
[[Prototype]]: Array(0)

I can't figure out what I'm doing wrong

async created() {
        this.stripe = this.$http.create({
            baseURL:  process.env.VUE_APP_STRIPE_URL,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Bearer ${process.env.VUE_APP_STRIPE_TOKEN}`
            }
        });
        await this.getStripeProducts();
        await this.getPaymentsLinks();
        this.getPaymentsLinkItems();
    },

Use Promise.all and Array.map() to have await calls run in parallel

async getPaymentsLinkItems() {
  let items = [];
  await Promise.all(this.paymentLinks.map(async (link) => {
    let object = {};
    let response = await this.stripe.get(`/payment_links/${link.id}/line_items`);
    items.push({[response.data.data[0].price.product]: link.url});
    object = {};
  }
  console.log(items);
}

or use for...of loop to have await calls run sequentially

async getPaymentsLinkItems() {
  let items = [];
  for(const link of this.paymentLinks) {
    let object = {};
    let response = await this.stripe.get(`/payment_links/${link.id}/line_items`);
    items.push({[response.data.data[0].price.product]: link.url});
    object = {};
  }
  console.log(items);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM