等待Function完成,然后返回一个值 [英] Wait for Function to complete and then return a value

查看:123
本文介绍了等待Function完成,然后返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个函数 Offline.check(); ,需要1秒才能执行..所以下面的函数没有等待它,它总是先返回false time.I使用set time out ..但那总是返回null。

I have this function Offline.check(); , which takes 1 seconds to execute..So below function is not waiting for it and it always return false on first time.I used set time out..but thats always returning null.

  function checkstats()

    {

    Offline.check(); // This returns Offline.state=up  or down and it takes 1 seconds to complete.

    if(Offline.state=="up")
    {
    return true;
    }

    else
    {
    return false;
    }

    }

var a = checkstats();


推荐答案

理想情况下,您可以使用<$ c设置回调函数$ c> Offline.check ,但我知道它是外部的,因此无效。

Ideally you could set a callback function with Offline.check, but I understand it is external, so that won't work.

您可以使用超时等待要设置 Offline.state ,但是你需要异步执行涉及变量 a 的任何操作:

You can use a timeout to wait for Offline.state to get set, but then you'll need to do any actions involving the variable a asynchronously too:

function checkstats(callBack){  // checkstats() now takes a callback
    Offline.check();  // Start Offline.check() as usual

    setTimeout(function(){  // Set a timeout for 1 second
        if(Offline.state=="up")  // After 1 second, check Offline.state as usual
        {
            callBack(true);  // ...but we call the callback instead of returning
        }
        else
        {
            callBack(false);  // ...but we call the callback instead of returning
        }
    }, 1000);
}

checkstats(function(a){ // This anonymous function is the callback we're using
    // Now you can use "a" normally
});

如果您不确定 Offline.check()正好1秒,您可以使用间隔而不是超时,并尝试每秒,比如5秒:

If you're not sure that Offline.check() will take exactly 1 second, you can use an interval instead of a timeout, and try every second for, say, 5 seconds:

function checkstats(callBack){
    Offline.check();

    var attempt = 0, maxAttempts = 5;
    var checkStatsInterval = setInterval(function(){
        if(++attempt > maxAttempts){
            // Ran out of attempts, just give up
            clearInterval(checkStatsInterval);
            alert('Waited '+maxAttempts+' seconds for Offline data. Giving up!');
            return;
        }
        if(Offline.state){
            clearInterval(checkStatsInterval);

            // It's loaded! Now confidently check Offline.state
            if(Offline.state=="up")
            {
                callBack(true);
            }
            else
            {
                callBack(false);
            }
        }
    }, 1000);
}

checkstats(function(a){
    // Now you can use "a" normally
});

这篇关于等待Function完成,然后返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆