dumb async questions

Hi, I never really was able to deeply await promises and async functions. I have a couple of questions on error handling. (axios) How can I save a variable from an async get or post using .then on the top scope. Is it possible to error handle an await statement instead of it always crashing my run
3 Replies
chnmrn.
chnmrn.17mo ago
i think u need to use try and catch. if it throw res status other than 2xx example: 401 or 500, it will be threated as error and the response or json they send back will go to err.response.data iirc(try consolelog)
fox-foxivich
fox-foxivich17mo ago
you can do something like that
import axios from "axios"

const getSomeResponse = () => {
return axios
.get("https://www.grepper.com/api/get_answers_1.php?v=4&s=axios&u=1300987")
.then((response) => response.data)
}

const yourCode = async () => {
let yourResponse

try {
const response = await getSomeResponse()
yourResponse = response
} catch (error) {
console.error(error)
}
}

const yourCodeWithThens = () => {
let yourResponse

getSomeResponse()
.then((response) => {
yourResponse = response
})
.catch((error) => {
console.error(error)
})
}
import axios from "axios"

const getSomeResponse = () => {
return axios
.get("https://www.grepper.com/api/get_answers_1.php?v=4&s=axios&u=1300987")
.then((response) => response.data)
}

const yourCode = async () => {
let yourResponse

try {
const response = await getSomeResponse()
yourResponse = response
} catch (error) {
console.error(error)
}
}

const yourCodeWithThens = () => {
let yourResponse

getSomeResponse()
.then((response) => {
yourResponse = response
})
.catch((error) => {
console.error(error)
})
}
just create a variable in the scope above and in the then scope assign your response to the variable. And also there's try catch for errors with async/await and there's .catch() method in the regular promises
s☻d
s☻d17mo ago
Thank you so much for the code snippets, I was trying to do the second example earlier but I ran into weird undefined issues. I just used try and catch to fix most of my issues
Want results from more Discord servers?
Add your server