【问题标题】:array push in the async function is not assigned to the external variable [duplicate]异步函数中的数组推送未分配给外部变量[重复]
【发布时间】:2020-10-17 21:40:33
【问题描述】:

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

我遇到的问题与 utils 无关。问题是异步函数中的array push

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

但是,正在使用地图功能:)

我该怎么办?

/* 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);
}

【问题讨论】:

  • 这个我看过了,不明白要不要用superagent
  • 我不知道superagent 是什么。但是您的代码显示出对异步代码的一个非常常见的误解 - 不清楚您的目标是什么,但通过阅读链接问题的最佳答案,您应该会得到一些好主意。
  • 你在这里误用了.map().map() 用于将一个数组转换为另一个数组。如果您只是想要副作用,请使用for..of,但这里有一种方法可以有效地使用.map()

标签: javascript api fetch-api


【解决方案1】:

试试这个方法:

/* 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);
}

【讨论】:

    【解决方案2】:

    最好的办法是使用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);
    }
    

    此外,您当前的解决方案不起作用的原因是,您的代码中没有任何内容表明在 @ 回调之外的函数末尾调用 myPostsAll 之前等待 myPostsAll 完成987654326@函数:

    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);
    }
    

    参考资料:

    【讨论】:

    • 我不明白如何在异步函数中使用它。成功了,感谢您的经验和帮助。 :)
    • @YasinATEŞ 查看编辑了解更多说明
    猜你喜欢
    • 2020-10-05
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多