0

是uni-app制作微信小程序,遇到网络请求异步、同步的问题?

1、使用默认的uni.request请求

uni.login({
    provider: 'weixin',
    success: function (loginRes) {
        let code = loginRes.code
        
        uni.request({
            url: apiurl+"/oauth/oauth",  
            data: {code:code},
            method:'POST',
            success: (res) => {  
                console.log(res.data); 
                 if (res.data.status == 1) {
                    var results=res.data.results
                    console.log("==============================")
                    $vm.$store.commit('setSessionkey',results.sessionkey)
                    console.log("sessionkey1:"+$vm.sessionkey)
                 }
            }
        })
        console.log("sessionkey2:"+$vm.sessionkey)

    }
})

如下图,sessionkey2为空
图片描述

2、根据百度搜索后,尝试对uni.request请求进行封装

//封装uni.request
export async function post_request(url, obj) {  
    //返回一个promise实例。  
    return await new Promise((resolve, reject) => {  
        uni.request({  
            url: apiurl+url,  
            data: obj,
            method:'POST',
            success: (result) => {  
                resolve(result.data);  
            },
            fail: (e) => {  
                reject(e);  
            }  
        })  
    })  
} 
//请求数据
uni.login({
    provider: 'weixin',
    success: function (loginRes) {
        let code = loginRes.code
        
        post_request("/oauth/oauth",{code:code}).then(res => {
            console.log(res)
            if (res.status == 1) {
                var results=res.results
                console.log("==============================")
                $vm.$store.commit('setSessionkey',results.sessionkey)
                console.log("sessionkey1:"+$vm.sessionkey)
            }
        })
        console.log("sessionkey2:"+$vm.sessionkey)
    }
})

如下图,sessionkey2还是为空的
图片描述

求助,如何才能让sessionkey2正常输出呢?

nemesiszh 329
2019-09-11 提问

查看全部 5 个回答

0
export function Promisify(func) {
  return function(data) {
    return new Promise((resolve, reject) => {
      func({
        ...data,
        success: resolve,
        fail: reject
      });
    });
  };
}

const func = Promisify(uni.request);
const rsp = (await func(options)).data;

推荐答案

1

简单例子,使用 Promise async await

;(async function () {
  // 2 秒后返回结果
  function demo (msg) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(`[ok]:${msg}`)
      }, 2000)
    })
  }

  const test = await demo('异步变同步成功')
  alert(test)
})();

推广链接