繁体   English   中英

Php Guzzle的异步请求无法正常工作

[英]Async requests with Php Guzzle are not working async

我在下面创建代码,以发出异步请求以从API获取数据。

<?php
require 'vendor/autoload.php';
$url = "https://pucminas.instructure.com/api/v1/";

$client = new GuzzleHttp\Client(['base_uri' => $url]);

$headers = [
    'Authorization' => "Bearer 11111~dsgffdhstggfjsdhf",
    'Accept'        => 'application/json',    
];

$course_id = "2242";
set_time_limit(300);

$promise = $client->getAsync( 'courses/'.$course_id.'/students/submissions?student_ids[]=all&grouped=true&post_to_sis=false&enrollment_state=active&include[]=user&include[]=assignment&include[]=total_scores&per_page=1000', ['connect_timeout' => 600, 'headers' => $headers]);

$promise
->then(function ($response) {
echo 'Got a response! ' . $response->getStatusCode();
});

?>
<h2>Reports</h2>

我想当我加载页面时,它将在页面中显示文本“ Reports”,并且从API获取内容后(至少需要60秒),它将显示消息“获得响应”,但不会那样工作。

首先,页面从API加载内容,然后才同时显示文本“ Reports”和“ Got a message”。

我希望在加载页面时立即显示文本“报告”,而仅在从API加载数据时才显示文本“获得响应”。

我怎样才能做到这一点?

您只能从PHP脚本发送一个响应,即您的浏览器请求一个页面,PHP服务器将构建该页面并将其发送回。 由于HTTP是无状态的,因此PHP服务器无法将页面更新“推送”到浏览器。

要实现您想要的功能,您需要编写一些JavaScript,这些JavaScript将调用PHP脚本来启动“大量异步承诺”。 然后,该诺言将在诺言完成后将结果写入文件(或数据库)。

然后,您需要第二个javascript函数,该函数会不断检查第二个php脚本。 第二个PHP脚本将检查文件的内容(或数据库条目等)并返回结果。

您可能最好看一下Axios之类的东西,并且完全丢掉PHP

https://www.npmjs.com/package/axios

暂无
暂无

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

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