鍍金池/ 問答/HTML/ 微信小程序如何把接口調(diào)用成功的回調(diào)函數(shù)返回的參數(shù)return出去?

微信小程序如何把接口調(diào)用成功的回調(diào)函數(shù)返回的參數(shù)return出去?

想寫個(gè)獲取用戶所在地的公共函數(shù),我目前是這樣寫的,因?yàn)楫惒秸?qǐng)求的原因return的data沒賦上值,打印locationData就理所應(yīng)當(dāng)?shù)氖莡ndefined了。想求教下各位大神要怎樣寫才能return出去success里返回的數(shù)據(jù)?


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);
}
回答
編輯回答
離夢(mèng)

用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);
    })
}
2017年8月7日 22:08