vue在多方法执行完后再执行另一个方法(等待请求完数据再执行)async/await使用方法和Promise.all

29 篇文章 1 订阅
8 篇文章 0 订阅

vue在一个方法执行完后执行另一个方法

用Promise.all来实现。
Promise是ES6的新特性,用于处理异步操作逻辑,用过给Promise添加then和catch函数,处理成功和失败的情况

ES7中新提出async搭配await,建议使用async搭配await。

function fun1(){
    return new Promise((resolve, reject) => {
        /* 你的逻辑代码 */
        console.log("1");
    });
},
function fun2(){
    return new Promise((resolve, reject) => {
        /* 你的逻辑代码 */
        console.log("2");
    });
},
function fun3(){
    return new Promise((resolve, reject) => {
        /* 你的逻辑代码 */
        console.log("3");
    });
},
/* 调用 */
function run(){
    Promise.all([
        this.fun1(),
        this.fun2(),
        this.fun3()
    ]).then(res => {
        /* 你的逻辑代码 */
        console.log("run");
    })
}

async/await使用方法

//示例1

async function testSync() {
   const response = await new Promise(resolve => {
       setTimeout(() => {
           resolve("async await test...");
         }, 1000);
    });
      console.log(response);
 }
 
testSync();//async await test...

//示例2

async getScheduleList(selectDate) {
	let response;
	// 这里request为向服务的发请求的方法
	await request(api.getScheduleList, {
		date: selectDate
	}).then(res => {
		response = res;
	});
	return response
}

init() {
	this.getScheduleList(selectDate).then(res => {
		console.log(res)
	})
}

//示例3

swichMenu: async function() {
	//点击其中一个 menu
	const num = await  getNum()
	return num
}

swichMenu().then(res => {
	console.log(res)
})

 

  • 6
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1学习者1

打赏作者一杯咖啡与妹子坐坐吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值