最近搜索

小程序 请求代码 如何写成同步 get请求 同步 post 请求同步

浏览:14
管理员 2025-08-05 17:51






    const res = await get_qr(obj);
    if (res.data.success) {
      qrUrl = res.data.indexUser.qrUrl;
    }
    console.log(qrUrl);
    console.log("2222222");
    
    
    如果这样写 方法头写成这样。
      async click_share_pyq() {

image.png


这样代码就同步了。  如果不这样写,我们的代码会想执行22222  在输入图片地址。




更完整的代码这样写。

async click_share_pyq() {
  // ...省略其他逻辑
  try {
    const res = await get_qr(obj);
    if (res.data.success) {
      qrUlr = res.data.indexUser.qrUrl;
      wx.onMenuShareTimeline({ title, link: qrUlr, imgUrl });
    }
  } catch (error) {
    console.error('获取二维码失败:', error);
  }
}






另外一个案例

Component({
  lifetimes: {
     attached:  function () {
      console.log("在组件实例进入页面节点树时执行");
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
      const currentMonthStr = `${year}-${month}`;//2025-03
      //请求这个月份的 价格 和禁用日期。

      console.log("1");
      const res =   this.getGoodsPrice(1,"");
      const res2 =   this.getGoodsPriceJin(1,""); 
      console.log("2");
      
      
      
   这个为什么执行了 1 2  在执行网络请求
    
    async getGoodsPrice(taocanId,month){
      var obj = {};
      obj.page=1;
      obj.limit=10
      const res = await goods_price_list(obj);
      console.log("111",res);
      return res;
    },
    async getGoodsPriceJin(taocanId,month){
      var obj = {};
      obj.page=1;
      obj.limit=10
      const res = await goods_price_list(obj);
      console.log("222",res);
      return res;
    },
    
    
    
    正确的写法是,改3个地方。
    attached: async function () {
           const res = await this.getGoodsPrice(1,"");
      const res2 = await this.getGoodsPriceJin(1,""); 
      
      这样改执行顺序就对了。
      11

前面有个1 输出

image.png



更好的写法,可以这样写。

 attached: async function () {
 
 
console.log("1");
const [res, res2] = await Promise.all([
  this.getGoodsPrice(1,""),
  this.getGoodsPriceJin(1,"")
]);
console.log("2");


联系站长

站长微信:xiaomao0055

站长QQ:14496453