async await 最常见的是在云函数内的使用

  • await 只能用于 async 函数内部
  • await 使用的精髓在于,紧随 await 之后的函数或是其他类型,产生的结果,一旦被调用就会立即计算出结果,供调用者使用。
`resData 一旦被使用,即使只是打印了一下,也会优先于 for 循环,先行处理`
exports.main = async (event, context) => {
	let resData = await db.collection('demo').field({_id:0}).get();	
	console.log("是我调用await结果的,我先",resData);
	for(let i =0;i<10;i++){
		console.log('我想先执行可以吗?',i)
		}
	return{
		code:200,
		msg:'请求成功',
		resData
	}
}	

async await 在 methods 内使用

  • 在一个方法的内部使用 async await
  • 这个方法在等待另一个方法的结果
methods: {
  'myRequest()函数内部,需要等待网络请求出结果了'
  '再把数据返回给其他函数调用处'
  async myRequest(val) {
	const [Error, res] = await uni.request({
		url: '/autonumber/autoComNum',
		method: 'GET',
		data: {
			text: val
			}
		});
		let data = res.data;
		let err = Error;
		return { data, err };
	},
	'检查验证数据的checkNumB()函数内部'
	'需要等待三个函数的结果,才能进行下一步'
  async checkNumB() {
	/*检测快递单号的长度*/
	let checkLength = await this.checkLength(this.numB);
	if (!checkLength) {
		this.remove();
		console.log("单号长度有误")
		return;
	} /*检测快递单号是否重复*/
	let myforArr = await this.forArr(this.numB);
	if (!myforArr) {
		this.remove();
		console.log('单号重复');
		return;		
	}
	/*网络检测快递单号是否正确*/
	let { data, err } = await this.myRequest(this.numB);
	if (data) {
		this.expressName = data;
		this.isRequest = true;
		} else {
			console.log(err);
			this.wrong += 1;
			this.isRequest = false;
			this.expressName = '-未知-';
		}
		this.totalCount();
	},
  'forArr()是一个普通函数'
  forArr(e) {
	var arr = this.buffNumArr.filter(k => {
		return k === e;
	});
	if (arr.length !== 0) {
		this.isFalse = true;
		this.num += 1;
		this.wrong;
		return false;
	} else {
		return true;
	}
  },
  'checkLength()是一个普通函数'
  checkLength(e) {
	if (e.length < 12) {
		this.wrong += 1;
		this.countdown = `快递单号长度有误${this.wrong}次`;
		this.istrue = true;
		return false;
	    } else {
		  return true;
	   }
   }
}		
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐