Merge pull request #195 from zcmzc/patch-2

Optimized retry() function
This commit is contained in:
黄朝晖 2019-07-12 17:20:52 +08:00 committed by GitHub
commit acd8515d45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 3 deletions

View File

@ -4,6 +4,10 @@
- [#185](https://github.com/hyperf-cloud/hyperf/pull/185) Added support for xml format of response.
# Changed
- [#195](https://github.com/hyperf-cloud/hyperf/pull/195) Changed the behavior of parameter `$times` of `retry()` function, means the retry times of the callable function.
## Fixed
- [#176](https://github.com/hyperf-cloud/hyperf/pull/176) Fixed TypeError: Return value of LengthAwarePaginator::nextPageUrl() must be of the type string or null, none returned.

View File

@ -72,15 +72,13 @@ if (! function_exists('retry')) {
*/
function retry($times, callable $callback, $sleep = 0)
{
--$times;
beginning:
try {
return $callback();
} catch (\Throwable $e) {
if ($times <= 0) {
if (--$times < 0) {
throw $e;
}
--$times;
if ($sleep) {
usleep($sleep * 1000);
}

View File

@ -58,6 +58,22 @@ class FunctionTest extends TestCase
++$result;
throw new RetryException('Retry Test');
});
} finally {
$this->assertSame(3, $result);
}
}
/**
* @expectedException \HyperfTest\Utils\Exception\RetryException
*/
public function testOneTimesRetry()
{
$result = 0;
try {
retry(1, function () use (&$result) {
++$result;
throw new RetryException('Retry Test');
});
} finally {
$this->assertSame(2, $result);
}