node.js - 无法访问“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 尚未解决此问题。非常感谢任何帮助:)
解决方案
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”也可能未定义。您能否让您的代码沿着承诺链进行,因为这正是这些编程结构试图解决的问题......?
推荐阅读
- asp.net - 交替处理发布和获取操作的“最佳”方式是什么?
- c# - 如何修复两页上的死锁?
- mysql - 如何在第一个分隔符后显示列数据
- c++ - 在 Qt QGraphicsItem 中实现 OpenGL 推荐
- asynchronous - 在 RxJS Observable flatMap 中运行 await
- javascript - 检查 Gridview 中的复选框(在标题模板中)和其他 Chekcboxes(在项目模板中)也被检查 jquery
- django - TestCase 中的 IntegrityError 在更新到 Django 2.0 后运行
- python - 在 Chrome 无头模式下在 Python 中使用 Selenium 抓取 AngularJS
- c# - 使用 INSERT 语句时如何修复“SQLite 异常,提供给命令的参数不足”
- c# - C# 读取进程内存