首页 > 解决方案 > 为什么我不能重新定义 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。尝试其他帐户用户名未定义

标签: javascriptnode.js

解决方案


所做的是,如果.catch它被调用的 Promise 被拒绝,则将catch其转换为 Promise,该 Promise解析catch. 由于您catch没有返回任何东西,尽管您重新分配Bodynull,一旦.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")


推荐阅读