Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

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
    }
})()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...