-
Notifications
You must be signed in to change notification settings - Fork 3
/
async-await-fetch.php
58 lines (47 loc) · 1.93 KB
/
async-await-fetch.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
// Instead of yield generators, now users can use modern Async/Await syntax
include dirname(dirname(dirname(__FILE__))) . '/ccxt.php';
use function React\Async\async;
use function React\Async\await;
date_default_timezone_set('UTC');
$exchange = new ccxt\async\binance([]);
await($exchange->load_markets());
$symbols = array('BTC/USDT', 'ETH/USDT');
// ###########################################
echo "########## Individual await ##########\n";
foreach ($symbols as $symbol) {
$ticker = await($exchange->fetch_ticker($symbol));
echo "{$ticker['symbol']} {$ticker['close']}\n";
}
// ###########################################
// ###########################################
echo "########### Combined await ###########\n";
$promises = [];
foreach ($symbols as $symbol) {
$promises[] = $exchange->fetch_ticker($symbol);
}
$tickers = await(React\Promise\all($promises));
echo "{$tickers[0]['symbol']} {$tickers[0]['close']} | {$tickers[1]['symbol']} {$tickers[1]['close']}\n";
// ###########################################
// ###########################################
$exchange->fetch_ticker($symbols[0])->then(function($ticker){
echo "########## Callback->then ##########\n";
echo "{$ticker['symbol']} {$ticker['close']}\n";
});
// ###########################################
// ################### custom async function ########################
function myFunc ($exchange, $symbol) {
return async(function () use ($exchange, $symbol) {
try {
// example sleep
await(React\Promise\Timer\sleep(0.5));
$ticker = await($exchange->fetch_ticker($symbol));
echo "########## Custom async function ##########\n";
echo "{$ticker['symbol']} {$ticker['close']}\n";
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
}
});
}
await(myFunc($exchange, $symbols[0])());
// ###########################################