小程序不支持wx.request同步请求解决方法


小程序为了用户体验,所有的request均为异步请求,不会阻塞程序运行

百牛信息技术bainiu.ltd整理发布于博客园

所以当你需要同步请求,锁死操作时,最好将所有的逻辑写在success:function(){}

里面,

不然后出现返回值为空的尴尬

错误代码示例:

更改后的代码为:

  1. onShow:function(){
  2. // 页面显示
  3. var commonFunction = require('../../pages/index/common'),
  4. that = this;
  5. var interval = setInterval(function(){
  6. that.setData({
  7. nowTime : commonFunction.formatTime(new Date())
  8. })
  9. },1000);
  10. var request = function(latitude,longitude){
  11. wx.request({
  12. url: that.globalData.API_URL + 'getLocation',
  13. data: {
  14. latitude : latitude,
  15. longitude : longitude
  16. },
  17. method: 'GET',
  18. success: function(res){
  19. let result = res.data.data;
  20. result = JSON.parse(result);
  21. console.log(result);
  22. }
  23. });
  24. };
  25. wx.getLocation({
  26. "type" : 'gcj02',
  27. "success" : function(res){
  28. const latitude = res.latitude;
  29. const longitude = res.longitude;
  30. request(latitude,longitude);
  31. },
  32. "fail" : function(e){
  33. console.log(e);
  34. }
  35. });
  36. },
  37. 此文作用仅为填坑,


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM