简体   繁体   English

function 没有返回值 React

[英]function does not return value React

I have a function where I form the current sum of elements.我有一个 function,我在其中形成当前的元素总和。 Getcoin is the method in my Api, and it works correctly if I console.log each element during the foreach cycle. Getcoin 是我的 Api 中的方法,如果我在 foreach 循环期间 console.log 每个元素,它可以正常工作。 But as the result I got nothing in the return and console.log function但结果我在返回和 console.log function 中一无所获

getCurrentCost() {
        let currentCostArr = [];
        let sum = 0;
    
        let existingEntries = JSON.parse(localStorage.getItem("walletData"));
        if (existingEntries == null) existingEntries = [];
    
        existingEntries.forEach(el => {
          this.coincapService
            .getCoin(el.id)
            .then((element) => {
              currentCostArr.push(element.priceUsd * el.amount)
            })
        });
    
        for (let i = 0; i < currentCostArr.length; i++) {
          sum += +currentCostArr[i];
        }
        console.log('cevf c ' + sum)
        console.log('current cost ' + currentCostArr)
    
        return currentCostArr;
      }

getCoin method getCoin方法

 getCoin = async (id) => {
    const coin = await this.getResource(`/assets/${id}`);
    return this._transformCoin(coin);
  }

The problem is that you are not handling correctly the Promise that .getCoin() returns inside the .forEach() 'loop'.问题是您没有正确处理.getCoin().forEach() “循环”内返回的 Promise。 It's making multiple calls to getCoin but the code outside the forEach is not awaiting these multiple async calls, so the next lines will execute without awaiting the result of the Promises.它对getCoin进行了多次调用,但forEach外部的代码并未等待这些多次异步调用,因此下一行将在不等待 Promises 结果的情况下执行。 This is causing confusion in execution order logic of your code, behaving different than what you are expecting.这会导致代码的执行顺序逻辑混乱,表现与您预期的不同。 Actually the function getCurrentCost() is ending before the Promises inside the loop resolves.实际上 function getCurrentCost() 在循环内的 Promises 解析之前结束。

One way to solve your problem is replacing the .forEach() with .map() , which will return several Promises that will be awaited will Promise.all() , behaving the way it's expected.解决问题的一种方法是将.forEach()替换为.map() ,这将返回几个将等待的Promise.all() ,其行为符合预期。

//don't forget to turn the function async, so you can use await keyword.
async getCurrentCost() {

  let sum = 0;  
  let existingEntries = JSON.parse(localStorage.getItem("walletData"));
  if (existingEntries == null) existingEntries = [];
    
  await Promise.all(existingEntries.map(async (el) => {
    const coin = await this.coincapService.getCoin(el.id)
    currentCostArr.push(coin.priceUsd * coin.amount)
  })
  
  return currentCostArr
}

Your forEach loop pushes values in you array asynchronously.您的forEach循环将值异步推送到您的数组中。

You calculate the sum before you get your array filled up with values.在让数组充满值之前先计算总和。

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

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