[英]Meteor.setTimeout return after the timeout
我有這個開關盒
var res=null;
switch(case){
case "Delay":
console.log("Start Delay");
var timer = Meteor.setTimeout(function(){
console.log("done Delay");
res="sample";
},15000);
console.log("test Delay");
break;
}
return res;
上面的代碼將記錄“啟動延遲”和“測試延遲”。 然后它將啟動計時器。 15000毫秒后,它將記錄“完成延遲”。 這里的問題是res變量的返回。 在計時器啟動之前,它已經返回res,它為空。
超時后如何返回變量?
我也嘗試了建議的答案,這是我的超時和睡眠功能代碼,
var timeout = function(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var sleep = async function(fn, ...args) {
await timeout(3000);
return fn(...args);
}
我換了開關盒
var res=null;
switch(case){
case "Delay":
console.log("Start Delay");
sleep(function(){
console.log("done Delay");
res="sample";
},15000);
console.log("test Delay");
break;
}
return res;
但是res變量仍然返回null而不是“ sample”。
您的switch語句是異步的,不會等待超時完成才返回響應。
在這種情況下,您應該使用回調函數。 這是您可能要實現的目標的一個粗略示例:
var WorkWithResponse = function(response){
console.log(response)
}
var res=null;
var TestResponse = function(x, callback){
switch(x){
case "Delay":
console.log("Start Delay");
//This is the AngularJS $timeout service,
//replace with your own Meteor timeout method
$timeout(function(){
console.log('Delay over')
res="Response Here";
callback(res);
},5000)
console.log("test Delay");
break;
}
return res;
}
TestResponse("Delay",WorkWithResponse)
我使用npm的纖維/未來包裝。 這個包允許函數在返回值之前等待其異步調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.