微信小程序如何把接口调用成功的回调函数返回的参数return出去?

想写个获取用户所在地的公共函数,我目前是这样写的,因为异步请求的原因return的data没赋上值,打印locationData就理所应当的是undefined了。想求教下各位大神要怎样写才能return出去success里返回的数据?


public.js:

var QQMapWX = require('qqmap-wx-jssdk.js'); //引入官方插件
var qqmapsdk = new QQMapWX({ key: 'XXXXX-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX' });

function getLocation() {
    var data;
    wx.getLocation({
        type: 'wgs84',
        success: function (res) {
            let latitude = res.latitude;
            let longitude = res.longitude;
            qqmapsdk.reverseGeocoder({
                location: {
                    latitude: latitude,
                    longitude: longitude
                },
                success: function (res) {
                    data = res.result;
                }
            });
        },
    });
 
    return data;
}

index.js:

var publicJS = require('../utils/public.js');
 
locationSelect: function() {
    var locationData = publicJS.getLocation();
    console.log(locationData);
}
阅读 18.6k
1 个回答

用Promise

function getLocation() {
    return new Promise(function(resolve, reject){
         wx.getLocation({
            type: 'wgs84',
            success: function (res) {
                let latitude = res.latitude;
                let longitude = res.longitude;
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: latitude,
                        longitude: longitude
                    },
                    success: function (res) {
                        resolve(res.result);
                    }
                });
            },
        });
    })
   

}

index:js

var publicJS = require('../utils/public.js');
 
locationSelect: function() { 
    publicJS.getLocation().then(function(locationData){
        console.log(locationData);
    })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题