为什么承诺记录数据但 returns undefined with same data
Why does promise log data but returns undefined with same data
我有一个功能:
getCoordinates: function() {
geoLocation.getCurrentLocation().then(function(location) {
return "latitude: " + location.latitude + " longitude:" + location.longitude;
});
}
其中 returns 未定义,但当我改为:
getCoordinates: function() {
geoLocation.getCurrentLocation().then(function(location) {
console.log("latitude: " + location.latitude + " longitude:" + location.longitude);
});
}
和运行我得到的相同功能:
"latitude: 4X.XXXXXX longitude:-12X.XXXXXXX"
我不明白为什么在必须定义数据时返回未定义,否则它不会记录到控制台。这是某种时间问题吗?我错过了什么?
您只是 return
从 then
回调,而不是 getCoordinates
函数(实际上 return
没有任何东西,因此 undefined
).
This is unsolvable for asynchronous callbacks 一般。在您的情况下,最好的解决方案是简单地 return 您已经创建的承诺,它将实现您期望的未来价值。
getCoordinates: function() {
return geoLocation.getCurrentLocation().then(function(location) {
// ^^^^^^
return "latitude: " + location.latitude + " longitude:" + location.longitude;
});
}
我有一个功能:
getCoordinates: function() {
geoLocation.getCurrentLocation().then(function(location) {
return "latitude: " + location.latitude + " longitude:" + location.longitude;
});
}
其中 returns 未定义,但当我改为:
getCoordinates: function() {
geoLocation.getCurrentLocation().then(function(location) {
console.log("latitude: " + location.latitude + " longitude:" + location.longitude);
});
}
和运行我得到的相同功能:
"latitude: 4X.XXXXXX longitude:-12X.XXXXXXX"
我不明白为什么在必须定义数据时返回未定义,否则它不会记录到控制台。这是某种时间问题吗?我错过了什么?
您只是 return
从 then
回调,而不是 getCoordinates
函数(实际上 return
没有任何东西,因此 undefined
).
This is unsolvable for asynchronous callbacks 一般。在您的情况下,最好的解决方案是简单地 return 您已经创建的承诺,它将实现您期望的未来价值。
getCoordinates: function() {
return geoLocation.getCurrentLocation().then(function(location) {
// ^^^^^^
return "latitude: " + location.latitude + " longitude:" + location.longitude;
});
}