小程序按顺序同步执行的两种方式

小程序按顺序执行的两种方式

1.回调函数执行,后一个方法写到前一个的回调函数中从而实现顺序执行,缺点是嵌套太多,代码混乱

2.async-await 同步执行,此方法等待前面方法执行完毕才继续后续执行。代码可读性好

以检查文本安全性为例给出两种不同方式代码以供参考

回调方式

/**
 * 同步检查是否包含敏感词
 */

// async function checkString(content) {
//   try {
//     var res = await wx.cloud.callFunction({
//       name: 'checkString',
//       data: {
//         content: content,
//       }
//     });
//     if (res.result.errCode == 0)
//       return true;
//     return false;
//   } catch (err) {
//     console.log(err);
//     return false;
//   }
// }


	// pubcom: async function (e) {
	// 	wx.showLoading({
	// 		title: '加载中',
	// 		mask: true
	// 	})

	// 	var that = this
	// 	var doc_id = that.data.commentID
	// 	var content = that.data.comcon
	// 	var formId = e.detail.formId;
	// 	if (!content) {
	// 		return
	// 	}
	// 	var isCheck = await common.checkString(content);
	// 	if (!isCheck) {
	// 		wx.showToast({
	// 			title: '含有敏感词',
	// 			image: "/assets/icon/icon-warning.png",
	// 		});
	// 		return
	// 	}
    //后续代码


	

async-await

/**
 * 异步检查
 */
function checkString(content,success,fail){
  wx.cloud.callFunction({
    name: 'checkString',
    data: {
      content: content,
    }
  }).then(res => {
    console.log(res);
    if (res.result.errCode == 0)
			success(res);
  }).catch(err => {
    console.error(err);
		fail(err);
  });
}

pubcom: function (e) {
		wx.showLoading({
			title: '加载中',
			mask: true
		})

		var that = this
	
		var content = that.data.comcon
		
		if (!content) {
			return
		}
		common.checkString(content, function (res) { 
			//成功代码
		}, function (err) {
            //失败
			wx.showToast({
				title: '含有敏感词',
				image: "/assets/icon/icon-warning.png",
			});
			return});
	},
发布了85 篇原创文章 · 获赞 45 · 访问量 95万+

猜你喜欢

转载自blog.csdn.net/flysnownet/article/details/103031727