javascript - 为什么我不能重新定义 Body 变量?
问题描述
我正在尝试在 中重新定义 JavaScript 变量.catch
,但这不起作用。
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")
控制台输出:
C:\Users\Dimitri\Restra>node 。状态码响应为 404。尝试其他帐户用户名未定义
解决方案
所做的是,如果.catch
它被调用的 Promise 被拒绝,则将catch
其转换为 Promise,该 Promise解析为catch
. 由于您catch
没有返回任何东西,尽管您重新分配Body
给null
,一旦.catch
整个 Promise 链完成, 就undefined
被分配给Body
.
而是返回null
内部:catch
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")
推荐阅读
- docker - Docker 容器中的 AGI 不接收 DTMF 输入
- python - 展平包含列表的字典字典
- elasticsearch - 连接字段的文档计数不匹配
- gstreamer - 警告:错误的管道:没有元素“voaacenc”
- azure - 混合 Azure AD 加入域的多因素身份验证
- javascript - 动态添加按钮时,从 onclick 事件调用原型函数
- ghostscript - ps2pdf (ghostscript) 裁剪图像
- android - 缩小后的 ImageButton 透明度
- include - 什么时候应该使用#include 而不是#include-once?
- java - 解决Tomcat中的绑定异常