我的结果数组有一个问题,我最初想要的是这样的
$promises = [
'0' => $client->getAsync("www.api.com/opportunities?api=key&page=1fields=['fields']"),
'1' => $client->getAsync("www.api.com/opportunities?api=key&page=2fields=['fields']"),
'2' => $client->getAsync("www.api.com/opportunities?api=key&page=3fields=['fields']")
];
我在我的PHP脚本上做了一个do while循环,但它似乎运行了一个无限循环,这是它应该如何工作的。 首先,我运行初始请求,然后得到totalRecordCount=154,然后减去它到recordCount=100,如果差值为!=0,它再次运行它,并更改$pagenumber并将其推送到承诺中。
这是我的函数代码
function runRequest(){
$promises = [];
$client = new \GuzzleHttp\Client();
$pageCounter = 1;
$globalCount = 0;
do {
//request first and then check if has difference
$url = 'https://api.com/opportunities_dates?key='.$GLOBALS['API_KEY'].'&page='.$pageCounter.'&fields=["fields"]';
$initialRequest = $client->getAsync($url);
$initialRequest->then(function ($response) {
return $response;
});
$initialResponse = $initialRequest->wait();
$initialBody = json_decode($initialResponse->getBody());
$totalRecordCount = $initialBody->totalRecordCount;//154
$recordCount = $initialBody->recordCount;//100
$difference = $totalRecordCount - $recordCount;//54
$pageCounter++;
$globalCount += $recordCount;
array_push($promises,$url);
} while ($totalRecordCount >= $globalCount);
return $promises;
}
$a = $runRequest();
print_r($a); //contains array of endpoint like in the sample above
有一个无止境的循环,因为当总记录计数等于全局计数时,您一直在循环。 第3页及以上有0条记录,因此总数将为154条。 用>
替换>=
将解决循环问题。
但是,代码仍然不会像您期望的那样工作。 对于每个页面,您使用getAsync()
准备一个请求,然后立即执行wait()
。 then
语句不执行任何操作。 它返回响应,默认情况下它已经这样做了。 因此,实际上,这些都是同步请求。
给定页面大小不变,您可以根据第一个请求上给出的信息计算您需要的页面。
function runRequest(){
$promises = [];
$client = new \GuzzleHttp\Client();
$url = 'https://api.com/opportunities_dates?key='.$GLOBALS['API_KEY'].'&fields=["fields"]';
// Initial request to get total record count and page count
$initialRequest = $client->getAsync($url.'&page=1');
$initialResponse = $initialRequest->wait();
$initialBody = json_decode($initialResponse->getBody());
$promises[] = $initialRequest;
$totalRecordCount = $initialBody->totalRecordCount;//154
$pageSize = $initialBody->pageSize;//100
$nrOfPages = ceil($totalRecordCount / $pageSize);//2
for ($page = 2; $page <= $nrOfPages; $page++) {
$promises[] = $client->getAsync($url.'&page='.$page);
}
return $promises;
}
$promises = runRequest();
$responses = \Guzzle\Promise\unwrap($promises);
请注意,该函数现在以字符串的形式返回承诺而不是URL。
第一个承诺已经谈妥了,这并不重要。 unwrap
函数不会导致对第1页的另一个GET请求,而是返回现有响应。 对于所有其他页面,请求是同时完成的。