我有一种情况,我有一个循环,将从文件中读取数据块,将这些数据块发送到休息 api,然后继续直到 EOF,但我希望它在循环内是异步的,所以,我不必等到 API 响应读取下一个块。我一直在研究 Amphp 和 ReactPHP,因为我找不到解决方案,或者我不明白应该如何使用这些库。这是我正在做的伪。
<?php
while($file.read()){
$chunk = getNextChunk();
sendChunkAsync($chunk);
}
function getNextChunk(){
echo "reading next chunk";
// read next chunk of data
}
带有 amphp 的示例
function sendChunkAsync($chunk){
Loop::run(function () {
$uri = "https://testapi.com/api";
$client = new DefaultClient;
try {
$promises = $client->request($uri);
$responses = yield $promises;
echo "chunk processed";
} catch (Amp\Artax\HttpException $error) {
// log error
// $error->getMessage() . PHP_EOL;
}
});
}
在这种情况下,我希望(如果读取块比从 api 获得响应更快)是这样的,不要拿这个文学作品,我试图为你说明它。
读取下一个块
读取下一个块
已处理的块
读取下一个块
已处理的块
已处理的块