简体   繁体   English

Promise.all返回[[PromiseValue]],但我需要所有返回值的数组

[英]Promise.all returns [[PromiseValue]] but I need array of all returned values

I am trying to return array of json objects, but below code returns [[PromiseValue]] and data surely is there. 我试图返回json对象的数组,但下面的代码返回[[PromiseValue]],数据肯定在那里。

"results from function" “功能结果”

在此输入图像描述

How can I get array of json objects and set it to state 如何获取json对象数组并将其设置为state

NOTE: if I call .then(data => console.log(data)) inside getEndResults function that works but then I can't setState in there as it throws an error 注意:如果我在getEndResults函数中调用.then(data => console.log(data)) ,但是我无法在那里getEndResults ,因为它会抛出错误

Warning: setState(...): Can only update a mounted or mounting component. 警告:setState(...):只能更新已安装或安装的组件。 This usually means you called setState() on an unmounted component. 这通常意味着您在已卸载的组件上调用了setState()。 This is a no-op. 这是一个无操作。

getUserCredits = async (userId, creditId) => {
    return await fetch(
    `${someLink}/userId/${userId}/credit/${creditId}`,
        {
            method: "GET",
        }
    )
}

getEndResult = async () => {
    const userId = await this.getUserId(userId);
    const userData = await this.getUserData(userId);

    const checkData = await Promise.all(userData.checks.map(check => {
    return check.checkIds.map((checkIds) => {
        return this.getUserCredits(userId ,checkIds)
            .then(res => res.json())
            .then(data => console.log(data))
            // Can't setState here
            // .then(data => this.setState({ results: data }))
        })
    }))

    console.log(checkData);
}

You're creating a 2-dimensional array of promises, and then passing that into Promise.all. 你正在创建一个二维的promises数组,然后将它传递给Promise.all。 Promise.all only knows how to work with single-dimensional arrays, so what it sees is an array with things that aren't promises. Promise.all只知道如何使用单维数组,所以它看到的是一个不承诺的数组。 For non-promises, promises.all just immediately resolves to the value it was given. 对于非承诺,promises.all只是立即解析它给出的值。

You will need to flatten out your 2-d array before sending it to Promise.all. 在将其发送到Promise.all之前,您需要将二维数组展平。 If you have a polyfill for array.prototype.flatmap (which will soon be added to javascript, but isn't there yet), this can be done like: 如果你有一个array.prototype.flatmap的polyfill (很快就会添加到javascript中,但还​​没有),可以这样做:

const checkData = await Promise.all(userData.checks.flatMap(check => {
  return check.checkIds.map((checkIds) => {
    return this.getUserCredits(userId, checkIds)
      .then(res => res.json());
  });

If that function is not available to you, then you could write your own function for flattening a 2d array, something like this: 如果您无法使用该功能,那么您可以编写自己的函数来展平2d数组,如下所示:

function flatten(arr) {
  const result = [];
  arr.forEach(val => {
    if (Array.isArray(val)) {
      result.push(...val);
    } else {
      result.push(val);
    }
  });
  return result;
}

// used like:

const promises = flatten(userData.checks.map(check => {
  // ... etc
}));
const checkData = await Promise.all(promises);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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