如何利用await/async等待一个函数完成后再执行第二个函数? [重复]

问题描述 投票:0回答:1

我从 s3 存储桶获取元数据并将数据存储到数组中。然后,我使用这些数组来使用 console.log() 方法显示信息,但是数组始终为空,我需要在第二个函数开始之前填充数组,因为我需要计算出现在元数据。代码的总体思路如下:

//Arrays I am populating with metadata
const [s3MetaA, sets3MetaA] = useState([]);
const [s3MetaB, sets3MetaB] = useState([]);

  async function getMetadata() {
    const s3Meta = await list({prefix: '',});

    s3Meta.items.map(async (item) => { 
      const metaResults = await getProperties({
        key: item.key
      })

      //Sorts the metadata into seperate arrays
      first_function(metaResults);
    })

    //metaArrCount should already have arrays populated 
    second_function();
  }

  async function first_function(metaResults){
    //Populate Each Array with their appropriate infomation so as to be used for general 
    //information displays
    sets3MetaA((s3MetaA) => [
      ...s3MetaA,
      metaResults.metadata.a
    ]);}

  async function second_function(metaResults){
     //Array should be populated here so I can do stuff with it
     console.log("Meta_A" , s3MetaA)

   }

我一直在尝试使用承诺,但我无法弄清楚如何使其正常工作,因此任何有关如何解决我的问题的想法将不胜感激。

javascript async-await promise
1个回答
-1
投票

对于这种情况,请在每个“异步函数调用”之前添加

await
关键字,如下所示:

const [s3MetaA, sets3MetaA] = useState([]);
const [s3MetaB, sets3MetaB] = useState([]);

  async function getMetadata() {
    const s3Meta = await list({prefix: '',});

    Promise.all(s3Meta.items.map(async (item) => { 
      const metaResults = await getProperties({
        key: item.key
      })

      //Sorts the metadata into seperate arrays
      await first_function(metaResults);
    }));

    //metaArrCount should already have arrays populated 
    await second_function();
  }

  async function first_function(metaResults){
    //Populate Each Array with their appropriate infomation so as to be used for general 
    //information displays
    sets3MetaA((s3MetaA) => [
      ...s3MetaA,
      metaResults.metadata.a
    ]);}

  async function second_function(metaResults){
     //Array should be populated here so I can do stuff with it
     console.log("Meta_A" , s3MetaA)

   }

这里是 freeCodeCamp 的一篇关于它如何工作的好文章,用简单的语言编写:)快乐编码!

© www.soinside.com 2019 - 2024. All rights reserved.