要求:需要在页面加载的时候先执行函数doSomething,再执行其他函数
方法一:使用回调函数
mounted() {
this.doSomething(this.callback);
},
methods: {
callback(result){
console.log('接收到的结果为'+result);
},
doSomething(callback){
console.log('执行结束');
setTimeout(function(){
let result=1;
callback(result);
},5000)
},
}
先显示"执行结束",五秒后显示"接收到的结果为1"
具体用的时候可以在回调函数中可以执行其他函数
方法二:promise对象
promise是异步编程的一种解决方法。
所谓promise,简单说是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果,从语法上说,promise是一个对象,从它可以获取异步操作的消息,promise提供了统一的API,各种异步操作都可以用同样的方法进行处理
mounted() {
this.doSomething().then(result=>{
console.log('接收到的结果为'+result);
});
},
methods: {
doSomething(){
console.log('执行结束');
return new Promise(function(resolve){
setTimeout(function(){
let result=1;
resolve(result);
},5000);
});
},
}
先显示"执行结束",五秒后显示"接收到的结果为1"
具体使用时,result可以作为一个参数传给后调用的函数,然后直接在doSomething()里面调用
方法三:async(ES7)
async 是 ES7 才有的与异步操作有关的关键字,和 Promise 有很大关联
mounted() {
this.getListMyKnows();
this.doSomething();
},
methods: {
testAwait(){
console.log("开始执行!");
return new Promise((resolve) => {
setTimeout(function(){
resolve();
}, 5000);
});
},
async doSomething(){
await this.testAwait();
console.log("执行结束!");
},
}
async是最常用的异步执行的关键字了,打印窗口先显示"开始执行",过五秒显示"执行结束"
使用时直接按照需要执行的顺序按照格式写就好了