js使用定時函式執行非同步呼叫
阿新 • • 發佈:2020-12-23
要求:需要在頁面載入的時候先執行函式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"
方法三: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是最常用的非同步執行的關鍵字了,列印視窗先顯示"開始執行",過五秒顯示"執行結束"
使用時直接按照需要執行的順序按照格式寫就好了