苦苦挣扎(理解)PHP异步请求

我真的很难理解PHP异步请求的工作方式。 在我看来,在PHP中不能有任何真正的异步行为,因为要从异步请求接收响应,你必须延迟脚本的执行(基本上是阻塞),然后失败了目的..对吗?</ p>

我想从我网站上的页面做的是:</ p>


  1. 向(本地)控制器发起AJAX请求以启动远程 API
    请求</ li>
  2. 对远程API使用GuzzleHTTP请求循环</ li>
  3. 完成每个请求后,将结果发送到socket.io服务器,然后发送一条消息 回到监听客户端(发起AJAX请求的原始页面)</ li>
    </ ol>

    现在,我有这个工作 - 有一点需要注意:GuzzleHTTP请求不是异步的 远程API非常慢(通常需要大约10秒才能收到JSON响应)所以当有10个任务时,我与服务器的连接被冻结超过一分钟。 打开新的选项卡/窗口并尝试访问该站点会导致等待原始脚本运行完成。</ p>

    这似乎表明我误解了HTTP请求的工作原理。 我认为就服务器而言,每个浏览器窗口(或请求)是完全独立的,但从我看到的结果来看,也许情况并非如此?</ p>

    这 这就是为什么我开始研究异步请求并发现它们看起来并非如此......异步。</ p>

    所以我真正想要的是帮助弥补差距/误解 我的知识:</ p>


    • 为什么阻塞首先发生(就新的,完全独立的请求而言)</ li>
    • 我可能会在哪里 寻求实施解决方案。</ li>
      </ ul>
      </ div>

展开原文

原文

I'm really struggling to understand the way PHP asynchronous requests work. It seems to me that there cannot be any true asynchronous behaviour in PHP because to receive a response from an asynchronous request, you have to delay execution of the script (blocking, essentially) which then defeats the purpose.. right?

What I'm trying to do from a page on my site is:

  1. Initiate AJAX request to (local) controller to begin the remote API requests
  2. Use a loop of GuzzleHTTP requests to remote API
  3. Upon completion of each request, send the result to a socket.io server which then emits a message back to the listening client (the original page that initiated the AJAX request)

Now, I have this working - with one caveat: the GuzzleHTTP requests are not asynchronous and the remote API is very slow (usually takes around 10 seconds to receive the JSON response) so when there are 10 tasks, my connection to the server is frozen for over a minute. Opening new tabs/windows and trying to access the site results in waiting until the original script run has completed.

This seems to indicate that I misunderstood how HTTP requests work. I thought that each individual browser window (or request) was completely separate as far as the server is concerned but from the result I'm seeing, perhaps this is not exactly the case?

This is why I started looking into asynchronous requests and discovered that they don't really seem all that.. asynchronous.

So what I'm really looking for is help filling the gaps/misunderstandings in my knowledge of:

  • Why the blocking occurs in the first place (in terms of new, completely separate requests)
  • Where I might look to implement a solution.

dongwei9365
dongwei9365 不是真的,我没有查看细节,但AFAIK没有在单独的进程中运行请求。guzzle似乎使用的技巧是返回一个Promise实例,它在任务队列中引用。每次访问Promise时,都会通过挂钩几个回调来更新其状态。最终结果是您的请求调用(requestAsync)在发出请求之前返回,并且每次收到响应的块时,它都由额外的回调处理。它基本上是在间歇阶段聚集状态
接近 5 年之前 回复
duanbi9202
duanbi9202 “伪异步”就是我准备好的方式。我认为它在请求完成后使用闭包来模拟进程。
接近 5 年之前 回复
dongshi1934
dongshi1934 感谢@EliasVanOotegem的信息,我不知道。那是伪同步吗?
接近 5 年之前 回复
drwu24647
drwu24647 这并不完全正确:guzzle确实支持他们。当然,实现并不是真正的异步,但它实际上是相同的
接近 5 年之前 回复
douci4026
douci4026 PHP不会发出任何异步请求。AJAX使异步请求和每个请求分开。
接近 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问