javascript - 为什么 Promise 记录数据但返回相同数据的未定义

标签 javascript node.js promise nativescript

我有一个功能:

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”

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

最佳答案

您仅从 then 回调中返回,而不是从 getCooperatives 函数返回(实际上,该函数不返回任何内容,因此未定义)。

This is unsolvable for asynchronous callbacks一般来说。就您而言,最好的解决方案是简单地返回您已经创建的 promise ,该 promise 将在未来实现您期望的值(value)。

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

关于javascript - 为什么 Promise 记录数据但返回相同数据的未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133808/

相关文章:

Javascript ajax 调用不会触发 Django

Javascript:更改表格行 HTML

javascript - 为什么 Angular4 Router 在 <router-outlet> 之外渲染元素

http - 错误 TS2346 : Supplied parameters do not match any signature of call target

Javascript:在 Promise.all Map 函数中的每个请求后添加超时

javascript - 如何选择在函数中将变量分配给哪个参数? -Javascript

node.js - 在nodejs服务器上获取ajax发送数据

node.js - 为什么 MongoDB 中出现 UserNotFound 错误?

node.js - 无法使用 Mongoose 保存数据,面临架构问题

javascript - Bluebird promise 与 Swagger : return is not a function