简体   繁体   中英

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.

"results from function"

在此输入图像描述

How can I get array of json objects and set it to 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

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. 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. Promise.all only knows how to work with single-dimensional arrays, so what it sees is an array with things that aren't promises. For non-promises, promises.all just immediately resolves to the value it was given.

You will need to flatten out your 2-d array before sending it to 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:

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:

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

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