首页 > 解决方案 > 无法访问“then”之外的数据

问题描述

我有一个 POST 来表达的获取请求,然后使用“.then”从表达中捕获响应(和数据)。我希望能够将生成的 JSON 对象作为导出/导入传递给另一个组件,但我无法这样做,因为在“.then”之外无法访问返回的数据。这是我遇到的问题:

fetch("http://localhost:5000", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(newUser),
})
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    var currentUser = data;
    console.log(currentUser);//<---JSON object
  });

  console.log(currentUser);//<---undefined - Why?

返回 currentUser 尚未解决此问题。非常感谢任何帮助:)

标签: node.jsreactjsexpress

解决方案


currentUser 变量在您的示例中超出范围, .then {} 块有自己的范围,不会扩展到其父级。如果您在 fetch 块上方声明了变量,它将稍后可用,但执行很可能会在返回 promise 之前到达您的第二个 console.log,因为 fetch 是一个异步过程。您必须等待变量的响应才能获得其内容。

欢迎来到异步编程的复杂世界!这里有一些关于异步编程的资源https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous

var myId = 12345;
var id;
console.log("Fetching info on " + myId);

fetch("https://exampleapi.org/getjson.php?id=" + myId)
  .then(
    (successResponse) => {
      if (successResponse.status != 200) {
        console.log("failed to get a 200 response code");
        return null;
      } else {
        return successResponse.json();
      }
    },
    (failResponse) => {
      console.log("failed to get a response");
      //exit;
      return null;
    }
  )
  .then((data) => {
    if (data.id && data.id > 0) {
      console.log('In Block', data.id);
      id=data.id
    }
  });

console.log('First Try', id);

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function delayedGreeting() {
  console.log('Second Try', id);
  await sleep(2000);
  console.log('Finally!!!', id);
}

delayedGreeting();
console.log('Third try', id);

console.log 可能是:(假设数据在请求后 2000 毫秒收到)

"Fetching info on 12345"
"First Try" undefined
"Second Try" undefined
"Third try" undefined
"In Block" 12345
"Finally" 12345

由于网络拥塞或其他原因,“Finally”也可能未定义。您能否让您的代码沿着承诺链进行,因为这正是这些编程结构试图解决的问题......?


推荐阅读