async函数中的数组push没有赋值给外部变量

array push in the async function is not assigned to the external variable

我想用 API 获取数据。 Fecth 是我的工具,获取 API 数据。它在唯一的数组中工作,所以我在 javascript 下面的示例对象中使用了 fetch 函数。我的 utils 不是受支持的对象。

我遇到的问题与实用程序无关。问题是异步函数中的array push

数组推送在外面的映射功能不起作用:(

但是,正在使用 map 函数:)

在外面运行我应该怎么办?

/* eslint-disable */
import Fetch from '@/utils/fetch';

async function allPosts(req, res) {
  const myPostsAll = await Fetch(`${process.env.NEXT_PUBLIC_API_URL}/${process.env.NEXT_PUBLIC_API_USERNAME}`);

    const posts = [];

    myPostsAll.map(async (item) => {
        const { id } = item;
        const myPostRes = await fetch(`${process.env.API_URL}/${id}`);
        const myPost = await myPostRes.json();

        const { title, description, cover_image, body_html } = myPost;

        posts.push({
            id: id.toString(),
            title,
            thumbnail: cover_image,
            description,
            content: body_html,
        });

        // It's work
        console.log(posts);
    });

    // It's not work
    console.log(posts);
}

试试这个方法:

/* eslint-disable */
import Fetch from '@/utils/fetch';

async function allPosts(req, res) {
  const myPostsAll = await Fetch(`${process.env.NEXT_PUBLIC_API_URL}/${process.env.NEXT_PUBLIC_API_USERNAME}`);

    

    const posts=myPostsAll.map(async (item) => {
        const { id } = item;
        const myPostRes = await fetch(`${process.env.API_URL}/${id}`);
        const myPost = await myPostRes.json();

        const { title, description, cover_image, body_html } = myPost;

        return {
            id: id.toString(),
            title:title,
            thumbnail: cover_image,
            description,
            content: body_html}
        

        
    });



    // It's not work
    console.log(posts);
}

解决此问题的最佳方法是利用 Promise.all:

async function allPosts(req, res) {
    const myPostsAll = await Fetch(`...`);
  
    // use `Array.map` to create an array of
    // `Promise`s, then pass that array as an argument
    // to `Promise.all` which will wait for all 
    // `Promise`s to resolve and return an array of objects
    const posts = await Promise.all(
      myPostsAll.map(async (item) => {
        const { id } = item;
        const myPostRes = await fetch(`${process.env.API_URL}/${id}`);
        const myPost = await myPostRes.json();
        const { title, description, cover_image, body_html } = myPost;

        return {
          id: id.toString(),
          title,
          description,
          thumbnail: cover_image,
          content: body_html,
        }
      })
    );
    console.log(posts);
}

此外,您当前的解决方案不起作用的原因是因为您的代码中没有任何内容表明在函数外部调用 console.log(posts) 之前等待 myPostsAll 完成Array.map 函数的回调:

async function test() {
  const posts = [];
  
  // this is asynchronous, so it won't "wait"
  // to finish before moving to the next statement,
  // unless you apply the solution above with `Promise.all`
  // and `await`
  myPostsAll.map(async () => {
    const myPostRes = await fetch(`...`);
    posts.push(...);
  })

  // gets called prior to `myPostsAll.map` completing
  console.log("posts", posts);
}

参考文献: