点我去Gitee
点我去Gitee

async await promise 把回调函数的值传出去

原文连接:https://segmentfault.com/q/1010000015603464

async await promise 把回调函数的值传出去

一、async+await要点

保证await到promise的resove才进行下一步

二、把回调的值传出去的方法

.then(return a)里面的值想要return出去,就要通过return new Promise+resolve(a)的方法传出去,在接受的地方还需要用.then(data=>{a=data})的方法才能接受到想要return出去的值a

1、错误写法

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);
}

2、更改

把回调函数的值用 promise resolve出去 用async+await接受 或者 .then接受

public.js

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);
    })
}
posted @ 2021-09-09 10:34  biuo  阅读(438)  评论(0编辑  收藏  举报