return then promise 方法后的数组变量数据?

return array variable data after the then promise method?

我创建了一个新的 promise 函数来将异步地理定位设置为全局函数。

function getUsrLoc() {
return new Promise(function(resolve, reject) {
                    if(navigator.geolocation){
                        navigator.geolocation.getCurrentPosition(resolve)
                    } else {
                        reject('Geolocation is not supported by this browser or OS');
                    }
                });
}

现在我已经创建了一个函数来将坐标推送到一个新数组,同时在我 运行 .then 方法后返回具有预期数组项的新变量。

//push coordinates into new array

function showPosition(position) {
     var coordinates = new Array();
     coordinates.push(Math.floor(position.coords.latitude))
     coordinates.push(Math.floor(position.coords.latitude))
     console.log(coordinates);
     return coordinates;
}

现在我可以 运行 getUsrLoc() 函数上的 .then 方法并将 showPosition 函数作为参数插入。

getUsrLoc().then(showPosition);

现在 运行ning,我将坐标打印到控制台(在浏览器提示后),但不返回新的变量坐标。

coordinates;
//undefined

我在这里错过了什么?

您不能事先声明一个变量并期望它具有正确的值。您应该创建一个 then 处理程序来访问 coordinates 变量:

getUsrLoc()
  .then(showPosition)
  .then(function(coordinates) {
    // Do your stuff here
  });