我正在使用一个带有Javascript和fetch的APIRest,如下所示:
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值。
发布于 2018-09-21 04:22:46
在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
来测试它。
您的代码示例(undefined
):
var c;
Promise.resolve('hi').then((msg) => {
c = msg;
});
console.log(c);
在回调函数中:
var c;
Promise.resolve('hi').then((msg) => {
c = msg;
console.log(c);
});
编辑
作为您的评论的后续内容:
fetch我需要"c“的值,在”
“块之外
这是一个异步调用。这意味着所有全局代码(执行上下文)都将运行到完成,然后才允许回调(在本例中为微任务)继续执行。
正如其他人在评论中所说的那样,有很多问题和很好的答案来解释异步JavaScript。
只需跟随链接即可。
https://stackoverflow.com/questions/52432710
复制相似问题