Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

javascript - 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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. 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. Keep in mind that you can't use await in top level code, it can only be used inside an async function

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...