我正在尝试通过 API 返回一个变量,但是当我返回它时,它总是将其返回为 undefined
有函数:
function getCityName()
{
console.log("Trying to return city location...");
var url = util.format('https://api.truckyapp.com/v2/map/%s/resolve?x=%s&y=%s', game.game.name, data.position.X, data.position.Y);
fetch(url).then(function(data) {
return data.json();
}).then(function(parsed){
return parsed.response.poi.realName;
});
}
运行函数的代码:
var city = getCityName();
console.log("City name is: "+city)
信息:JSON 显示正确
答案 0 :(得分:1)
您需要从 getCityName 函数返回回调返回的最终值:
function getCityName()
{
console.log("Trying to return city location...");
var url = util.format('https://api.truckyapp.com/v2/map/%s/resolve?x=%s&y=%s', game.game.name, data.position.X, data.position.Y);
return fetch(url).then(function(data) {
return data.json();
}).then(function(parsed){
return parsed.response.poi.realName;
});
}
上面会导致 getCityName 返回一个 Promise。要获得城市的实际价值,您现在必须等待 Promise 解决(使用 await 或 then)。按照遵循的标准,它将是:
getCityName().then(city => {
console.log("City name is: "+city);
});
补充一下,因为 getCityName 会返回一个可能会拒绝的 Promise,所以在调用函数的同时添加一个 catch 块是明智的。