我正在使用 APIRest、Javascript 和 fetch,如下所示:
var c;
fetch('http://-:8080/CantidadPacientes')
.then(a => a.json())
.then( function(msg) {
c = msg;
});
console.log(c);
但是当我打印变量“c”时,我得到了未定义的结果。 我怎样才能得到变量c中msg的值。在执行 console.log("c") 之前,我需要在获取之外获取值 msg
最佳答案
当 fetch
解析 promise
时,console.log(c)
行已经被调用。
尝试将其移动到回调中:
var c;
fetch('http://-:8080/CantidadPacientes')
.then(a => a.json())
.then( function(msg) {
c = msg;
console.log(c);
});
您可以使用简单的 Promise.resolve
对其进行测试。
您的代码示例(未定义
):
var c;
Promise.resolve('hi').then((msg) => {
c = msg;
});
console.log(c);
在回调内部:
var c;
Promise.resolve('hi').then((msg) => {
c = msg;
console.log(c);
});
编辑
作为您评论的后续内容:
I need the value of "c", outside the block "fetch"
这是一个异步调用。这意味着所有全局代码(执行上下文)都将运行完成,然后回调(在本例中为微任务)才会被允许继续。
正如其他人在评论中所说,有很多问题和很好的答案来解释异步 JavaScript。
只需点击链接即可。
关于javascript - 如何在Javascript中获取promise后的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52432710/