微信小程序异步转同步promise的async和await

本文介绍了如何在前端项目中处理异步操作,特别是在批量导入图片时,通过使用async/await和云函数实现同步执行。通过`cloudGetPath`函数与云函数交互,确保所有图片处理按顺序完成,解决了异步可能导致的逻辑混乱问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异步是前端的本质,在项目中,有些业务逻辑就需要用到同步执行

Page({
  data: {
  },
  /**
   * 批量导入
   */
  muchclickimages() {
    var that = this;
    //选择文件(图片)
    wx.chooseMessageFile({
      count: 100,
      type: 'image',
      success(res) {
        console.log(res)
        //临时路径
        // console.log(res.tempFiles)
        main()//调用
        async function main(){
          for(var i =0;i<res.tempFiles.length;i++){
          	//await等待
            await that.cloudGetPath(res.tempFiles[i].name)
        }
       }
     })
  	},
  /**
   * 云函数通过名字获取地址
   * @param {*} name 
   * return 路径
   */
  cloudGetPath:function(name) {
    var that = this
    //return
    return new Promise(resolve=>{
      wx.cloud.callFunction({
        name: "getStudentData",
        data: {
          name: name
        }
      }).then(res=>{
        console.log(res)
        //在执行完成后resolve
        resolve()
      })
    })
  },
  onLoad() {
    this.muchclickimages()
  }
})

这样就可以解决异步的问题了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值