为什么承诺日志数据但返回undefined与相同的数据

时间:2016-12-14 02:25:22

标签: javascript node.js promise nativescript

我有一个功能:

getCoordinates: function() {
        geoLocation.getCurrentLocation().then(function(location) {
            return "latitude: " + location.latitude + " longitude:" + location.longitude;
        });
    }

返回undefined,但是当我改为:

getCoordinates: function() {
        geoLocation.getCurrentLocation().then(function(location) {
            console.log("latitude: " + location.latitude + " longitude:" + location.longitude);
        });
    }

并运行我得到的相同功能:

“纬度:4X.XXXXXX经度:-12X.XXXXXXX”

我不明白为什么在必须定义数据时它返回undefined,或者它不会记录到控制台。这是某种时间问题吗?我错过了什么?

1 个答案:

答案 0 :(得分:4)

您只是return来自then回调,而不是来自getCoordinates函数(事实上它不return,因此undefined )。

总的来说是{p> This is unsolvable for asynchronous callbacks。在您的情况下,最好的解决方案是简单地返回您已经创建的承诺,并且将履行您期望的价值。

getCoordinates: function() {
    return geoLocation.getCurrentLocation().then(function(location) {
//  ^^^^^^
        return "latitude: " + location.latitude + " longitude:" + location.longitude;
    });
}