价值迟到了吗? “下面的值是刚刚评估的" [英] Value arriving late? “Value below was evaluated just now”

查看:134
本文介绍了价值迟到了吗? “下面的值是刚刚评估的"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let currComp = this;
let projects = []
let dataArr = []    


async function getData() {
  let getProject =
    await axios.get('url', {
      auth: {
        username: 'username',
        password: 'pw'
      }
    })

  let projects = await getProject.data.value;
  let arr = []
  let KPIs = []

  projects.map(project => {
    let item = () => axios.get(`url`, {
      auth: {
        username: 'username',
        password: 'pw'
      }
    })

    arr.push(item)
    console.log('arr', arr)
  })

  let results = await axios.all(arr)

  results.map(result => {

    result().then(function(v) {
      KPIs.push(v.data.value)
    })
  })

}

getData();

我想做的是:

  1. 获取axios调用以获取项目的名称.

  1. get an axios call to fetch the name of the projects.

使用这些获取的名称来调用多个axios调用.这应该可以为我提供该项目的一些数据.

Use those fetched names to call multiple axios calls. This is supposed to give me some data from that project.

results = await axios.all(arr)包含的函数可为我提供对API调用的响应.

results = await axios.all(arr) contains functions that gives me the responses to the API call.

响应被推送到数组KPIs中.

The responses gets pushed in the the array KPIs.

当我最后尝试console.log('KPIs', KPIs)时,它给了我

When I try to console.log('KPIs', KPIs) at the end, it gives me

这似乎是一个空数组,但是当我打开它时,

which seems to be an empty array, but when I open it,

它实际上具有我想要的值.

it actually has the value that I want.

问题是,当我尝试在代码中使用此数组时,它只给我数组的第一项.

The problem is, when I try to use this array in my code, it only gives me the first item of the array.

我试图在线搜索此问题,但它只告诉我该值到来较晚.

I tried to search this issue online, and it only told me that the value is arriving late.

我想将完整的数组与完整的结果一起使用.

I want to use the full array with the full result.

我该如何解决?

推荐答案

results = await axios.all(arr)包含的功能可为我提供对API调用的响应.

results = await axios.all(arr) contains functions that gives me the responses to the API call.

是的,但是那毫无意义.您不需要返回响应的诺言的函数,也没有必要在函数数组上调用axios.all或等待它.

Yes, but that's pointless. You don't want functions that return promises for responses, and there's no use to call axios.all on array of functions or await that.

您将需要构建一个承诺数组,以及all()await 那个.

You will instead need to build an array of promises, and all() and await that.

您也不需要使用then.您可以简化很多代码:

You shouldn't need to use then either. You can simplify your code a lot:

async function getData() {
  const getProject = await axios.get('url', {
    auth: {
      username: 'username',
      password: 'pw'
    }
  });

  const projects = getProject.data.value;
  const promises = projects.map(project =>
    axios.get(`url`, {
      auth: {
        username: 'username',
        password: 'pw'
      }
    })
  );

  const results = await axios.all(promises)

  const KPIs = results.map(v => v.data.value);
}

这篇关于价值迟到了吗? “下面的值是刚刚评估的"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆