I am trying to redefine an JavaScript variable in an .catch
, but that does not work.
index.js:
const Restra = async function(username) {
let status;
const Fetch = require("node-fetch"),
Url = "https://instagram.com/" + username + "/?__a=1"
let Body = await Fetch(Url).then((res) => {
status = res.status
return res.json()
})
.catch((e) => {
if(status === 404) return console.error("Status Code response was 404. Try an other Account Username")
Body = null
})
return console.log(Body)
}
Restra("whaterverusernamethathopefullynotexists")
Console Output:
C:\Users\Dimitri\Restra>node. Status Code response was 404. Try an other Account Username undefined
What .catch
does is, if the Promise it's being called on rejects, the catch
turns it into a Promise that resolves to the value returned in the catch
. Since your catch
isn't returning anything, although you reassign Body
to null
, once the .catch
and the whole Promise chain finishes, the undefined
is assigned to Body
.
Return null
inside the catch
instead:
const Restra = async function(username) { const Url = "https://instagram.com/" + username + "/?__a=1" const Body = await fetch(Url).then((res) => { status = res.status if (status === 404) { console.error("Status Code response was 404. Try an other Account Username"); // Go to the catch: } return res.json() }).catch((e) => { return null; }) return console.log(Body) } Restra("whaterverusernamethathopefullynotexists")
A far as I understand you want to overwrite body with null
but you are returning the console.log()
before overwriting Body
so it never reaches that line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.