【问题标题】:Why does promise log data but returns undefined with same data为什么承诺记录数据但返回未定义的相同数据
【发布时间】:2016-12-14 02:25:22
【问题描述】:

我有一个函数:

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

返回未定义,但当我这样做时:

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

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

"纬度:4X.XXXXXX 经度:-12X.XXXXXXX"

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

【问题讨论】:

  • 您希望它返回数据,还是对数据的承诺?

标签: javascript node.js promise nativescript


【解决方案1】:

您只是来自then 回调的returning,而不是来自getCoordinates 函数(实际上return 没有任何东西,因此undefined)。

This is unsolvable for asynchronous callbacks 一般。在您的情况下,最好的解决方案是简单地返回您已经创建的承诺,并将在未来实现您期望的价值。

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

【讨论】:

  • 我已经尝试了您上面提供的解决方案。当我这样做时,承诺对象本身被返回:[object Promise]
  • 是的,这是意料之中的。您无法返回数据,因为它还不存在。请阅读链接的问题。
  • 你需要做getCoordinates().then(console.log),而不是console.log(getCoordinates()),并处理你没有立即得到日志的事实。
  • 好的,我现在明白这个问题了。谢谢哥们!
猜你喜欢
  • 2017-07-23
  • 2021-01-28
  • 2017-10-10
  • 2019-07-30
  • 1970-01-01
  • 2018-12-06
  • 2021-07-07
  • 1970-01-01
  • 2015-09-27
相关资源
最近更新 更多