如果第一个函数返回值,则检测第二个函数

时间:2012-07-06 09:24:44

标签: javascript jquery

我有一个JS函数可以进行ajax调用并连续运行

function First(ServerId)
{
    var CallServer = jQuery.ajax({
        type: "POST",
        url: "somefile.php",
        dataType: "json",
        success: function(response)
        {
           // do something here
           First(response.ServerId);
        }
    }};
}

somefile.php 中有一个60秒的睡眠定时器,因此ajax调用在60秒后返回响应。每次返回不同的服务器ID时。

现在我有另一个功能,我想做这样的事情

function Second()
{
   /*
   wait for 5 seconds to see if function First() has returned server id
   if (ServerIdIsReturned)
   {
         i) abort CallServer
        ii) make another Ajax call (CallServer2)
       iii) after CallServer2 is done, call CallServer with the returned ServerId
   }
   else
   {
         i) abort CallServer
        ii) make another Ajax call (CallServer2)
       iii) after CallServer2 is done, call CallServer with the ServerId as 0
   }       
   */
}

我不确定我是否已正确解释它,但如果函数Second()返回了新的服务器ID,我想检查函数First()并相应地继续进行。我想我需要使用setTimeout并分解Second()函数,但不确定。

我该如何做到这一点?

3 个答案:

答案 0 :(得分:2)

只需在第一个函数的成功块中调用第二个函数。

 success: function(response) {
      // do something here
      First(response.ServerId);
      // proceed further
      Second();
 }

要拨打延迟电话,请使用setTimeout(Second,5000);

答案 1 :(得分:0)

在调用之前将全局变量设置为false,并在调用返回时将其设置为true,然后您可以检查该变量

答案 2 :(得分:0)

为什么不使用jQuery ajax调用的内置超时功能 - 设置5秒超时然后添加错误处理程序 - 检查超时并再次调用(如果适用)。

var CallServer = jQuery.ajax({
        type: "POST",
        url: "somefile.php",
        timeout:5000,
        dataType: "json",
        success: function(response)
        {
           // do something here
           First(response.ServerId);
        },
        complete(jqXHR, textStatus)
        {
            if (textStatus === "timeout")
           {
               Second();
            }
        }
    }};
相关问题