简体   繁体   English

Meteor.setTimeout超时后返回

[英]Meteor.setTimeout return after the timeout

I have this switch case, 我有这个开关盒

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;

The code above will log "Start Delay" & "test Delay". 上面的代码将记录“启动延迟”和“测试延迟”。 Then it will start the timer. 然后它将启动计时器。 After 15000ms, it will log "done Delay". 15000毫秒后,它将记录“完成延迟”。 The problem here is the returning of res variable. 这里的问题是res变量的返回。 Before the start of the timer, it already return res which is a null. 在计时器启动之前,它已经返回res,它为空。

How can I return a variable after the timeout? 超时后如何返回变量?

I also tried the suggested answer, this is my code for timeout and sleep function, 我也尝试了建议的答案,这是我的超时和睡眠功能代码,

var timeout = function(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
var sleep = async function(fn, ...args) {
    await timeout(3000);
    return fn(...args);
}

I changed my switch case, 我换了开关盒

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;

But still the res variable returned null instead of "sample". 但是res变量仍然返回null而不是“ sample”。

Your switch statement is asynchronous and will not wait for your timeout to complete before returning your response. 您的switch语句是异步的,不会等待超时完成才返回响应。

You should make use of callback functions in this scenario. 在这种情况下,您应该使用回调函数。 Here is a rough example of what you are possibly trying to achieve: 这是您可能要实现的目标的一个粗略示例:

 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)

I used fibers/future package from npm. 我使用npm的纤维/未来包装。 This package allow functions to wait to its async call before returning a value. 这个包允许函数在返回值之前等待其异步调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM