在第二个函数中检测第一个函数是否返回值

Detecting in second function if first function has returned value

本文关键字:函数 是否 返回值 第一个 第二个 检测      更新时间:2023-09-26

我有一个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);
        }
    }};
}

在某些文件中.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()函数First()是否返回了新的服务器 ID,并相应地继续。我想我需要使用 setTimeout 并分解 Second() 函数,但不确定。

我怎样才能做到这一点?

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

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

为了进行延迟呼叫,只需使用setTimeout(Second,5000);

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

为什么不直接使用 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();
            }
        }
    }};