简体   繁体   English

Nodejs - 数组不返回任何内容

[英]Nodejs - array not returning anything

I'm trying to save the answer to my request with axios in an array, but I'm not getting it, is something wrong?我正在尝试将 axios 的请求的答案保存在一个数组中,但我没有得到它,有什么问题吗?

colorList = axios.get(colors);

let codes = [];

for (let i = 0; i < colorList.data.data.colors.length; i++) {
  codes[i].push(colorList.data.data.colors[i]);
}

console.log(codes);

The call is asynchronous meaning that you have to wait for your request to complete (or more accurately your promise from axios.get() to resolve) and do something with the result.该调用是异步的,这意味着您必须等待您的请求完成(或更准确地说,您的 promise 来自axios.get()来解决)并对结果做一些事情。 Your code right now runs synchronously.您的代码现在同步运行。

colorList = axios.get(colors).then(result =>{
  console.log(result)
});

EDIT: Or as a comment above noted, use an async/await setup.编辑:或者如上所述,使用 async/await 设置。 Keep in mind that you can't use await in top level code, it can only be used inside an async function请记住,您不能在顶级代码中使用 await,它只能在async function中使用

(async () => {
    try {
        const colorCodes = await axios.get(colors);
    } catch (e) {
        // handle error
    }
})()

As most comments pointed out, the mistake in your code is that you don't await for the async call to be completed.The way that js works when you use async code is that it jumps to the next line immediatelly while the async process continues.正如大多数评论指出的那样,您的代码中的错误是您没有等待异步调用完成。当您使用异步代码时,js 的工作方式是在异步过程继续时立即跳转到下一行. That's the point of Async code: You don't want your program to freeze in case of async call delays.这就是异步代码的重点:您不希望程序在异步调用延迟的情况下冻结。 I made a similar code example using numbersapi.我使用 numbersapi 做了一个类似的代码示例。

var axios = require('axios');

const axiosCallToArray = async () => {
  const result = await axios.get('http://numbersapi.com/42');

  const wordsArray = result.data.split(' '); // here i create an array breaking the sentence (returned as result from axios) into words.Every word is an element of the new array

  console.log(wordsArray);
};

axiosCallToArray(); //now console.log works fine. This is valid also for your code

If colorList.data.data.colors has values then try如果 colorList.data.data.colors 有值,然后尝试

codes.push(colorList.data.data.colors[i]);代码.push(colorList.data.data.colors[i]);

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

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