本文整理汇总了PHP中React\Promise\Deferred::promise方法的典型用法代码示例。如果您正苦于以下问题:PHP Deferred::promise方法的具体用法?PHP Deferred::promise怎么用?PHP Deferred::promise使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类React\Promise\Deferred
的用法示例。
在下文中一共展示了Deferred::promise方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
public function run()
{
$this->deferred = new Deferred();
$this->deferred->promise()->progress(function ($event) {
$this->data[$event['part']] = $event['data'];
unset($this->unsettled[$event['part']]);
if ($this->isEverythingHasBeenReceived()) {
$this->deferred->resolve();
}
})->then(function () {
if (isset($this->cancel_timer)) {
$this->loop->cancelTimer($this->cancel_timer);
unset($this->cancel_timer);
}
})->done(function () {
$response = call_user_func($this->then_callback, $this->data);
$headers = ['Content-Type' => 'text/plain'];
$this->response->writeHead(200, $headers);
$this->response->end($response);
}, function () {
$headers = ['Content-Type' => 'text/plain'];
$this->response->writeHead(404, $headers);
$this->response->end("Failed");
});
if (empty($this->requests)) {
$this->deferred->resolve();
} else {
$this->registerCancelTimer();
foreach ($this->requests as $request) {
$request->end();
}
}
return $this;
}
示例2: collectEvents
private function collectEvents($command, $expectedEndEvent)
{
$req = $this->client->createAction($command);
$ret = $this->client->request($req);
$id = $req->getActionId();
$deferred = new Deferred();
// collect all intermediary channel events with this action ID
$collected = array();
$collector = function (Event $event) use($id, &$collected, $deferred, $expectedEndEvent) {
if ($event->getActionId() === $id) {
$collected[] = $event;
if ($event->getName() === $expectedEndEvent) {
$deferred->resolve($collected);
}
}
};
$this->client->on('event', $collector);
// unregister collector if client fails
$client = $this->client;
$unregister = function () use($client, $collector) {
$client->removeListener('event', $collector);
};
$ret->then(null, $unregister);
// stop waiting for events
$deferred->promise()->then($unregister);
return $ret->then(function (Response $response) use($deferred) {
// final result has been received => merge all intermediary channel events
return $deferred->promise()->then(function ($collected) use($response) {
$last = array_pop($collected);
return new Collection($response, $collected, $last);
});
});
}
示例3: start
/**
* {@inheritdoc}
*/
public function start()
{
if (isset($this->deferred)) {
throw new \RuntimeException('Tasks is already started');
}
$this->deferred = new Deferred();
return $this->deferred->promise();
}
示例4: __construct
/**
* The option values for 'before', 'complete', 'error' and 'end' can be a
* callable, an associative array containing event data, or an array of
* event data arrays. Event data arrays contain the following keys:
*
* - fn: callable to invoke that receives the event
* - priority: Optional event priority (defaults to 0)
* - once: Set to true so that the event is removed after it is triggered
*
* @param ClientInterface $client Client used to send the requests.
* @param array|\Iterator $requests Requests to send in parallel
* @param array $options Associative array of options
* - pool_size: (callable|int) Maximum number of requests to send
* concurrently, or a callback that receives
* the current queue size and returns the
* number of new requests to send
* - before: (callable|array) Receives a BeforeEvent
* - complete: (callable|array) Receives a CompleteEvent
* - error: (callable|array) Receives a ErrorEvent
* - end: (callable|array) Receives an EndEvent
*/
public function __construct(ClientInterface $client, $requests, array $options = [])
{
$this->client = $client;
$this->iter = $this->coerceIterable($requests);
$this->deferred = new Deferred();
$this->promise = $this->deferred->promise();
$this->poolSize = isset($options['pool_size']) ? $options['pool_size'] : 25;
$this->eventListeners = $this->prepareListeners($options, ['before', 'complete', 'error', 'end']);
}
示例5: start
/**
* {@inheritdoc}
*/
public function start()
{
if (isset($this->deferred)) {
throw new \RuntimeException('Tasks is already started');
}
$this->deferred = new Deferred();
$this->process->start(function () {
$this->outputBuffer->enqueue(func_get_args());
});
return $this->deferred->promise();
}
示例6: add
/**
* Call curl_multi_add_handle().
* @param resource $ch
* @return PromiseInterface
*/
public function add($ch)
{
$deferred = new Deferred();
$errno = curl_multi_add_handle($this->mh, $ch);
if ($errno !== CURLM_OK) {
// @codeCoverageIgnoreStart
$msg = curl_multi_strerror($errno) . ": {$ch}";
$deferred->reject(new \RuntimeException($msg));
return $deferred->promise();
// @codeCoverageIgnoreEnd
}
$this->added[(string) $ch] = $ch;
$this->deferreds[(string) $ch] = $deferred;
return $deferred->promise();
}
示例7: search
public function search($searchTarget = 'ssdp:all', $mx = 2)
{
$data = "M-SEARCH * HTTP/1.1\r\n";
$data .= "HOST: " . self::ADDRESS . "\r\n";
$data .= "MAN: \"ssdp:discover\"\r\n";
$data .= "MX: {$mx}\r\n";
$data .= "ST: {$searchTarget}\r\n";
$data .= "\r\n";
$socket = $this->multicast->createSender();
// TODO: The TTL for the IP packet SHOULD default to 2 and SHOULD be configurable.
$timer = $this->loop->addTimer($mx, function () use($socket, &$deferred) {
$deferred->resolve();
$socket->close();
});
$deferred = new Deferred(function () use($socket, &$timer) {
// canceling resulting promise cancels timer and closes socket
$timer->cancel();
$socket->close();
throw new RuntimeException('Cancelled');
});
$that = $this;
$socket->on('message', function ($data, $remote) use($deferred, $that) {
$message = $that->parseMessage($data, $remote);
$deferred->progress($message);
});
$socket->send($data, self::ADDRESS);
return $deferred->promise();
}
示例8: loadEtcResolvConf
public function loadEtcResolvConf($filename)
{
if (!file_exists($filename)) {
return When::reject(new \InvalidArgumentException("The filename for /etc/resolv.conf given does not exist: {$filename}"));
}
try {
$deferred = new Deferred();
$fd = fopen($filename, 'r');
stream_set_blocking($fd, 0);
$contents = '';
$stream = new Stream($fd, $this->loop);
$stream->on('data', function ($data) use(&$contents) {
$contents .= $data;
});
$stream->on('end', function () use(&$contents, $deferred) {
$deferred->resolve($contents);
});
$stream->on('error', function ($error) use($deferred) {
$deferred->reject($error);
});
return $deferred->promise();
} catch (\Exception $e) {
return When::reject($e);
}
}
示例9: queryDnsSeeds
/**
* Connect to $numSeeds DNS seeds
*
* @param int $numSeeds
* @return \React\Promise\Promise|\React\Promise\PromiseInterface
*/
public function queryDnsSeeds($numSeeds = 1)
{
$peerList = new Deferred();
// Take $numSeeds
$seedHosts = self::dnsSeedHosts();
$seeds = array_slice($seedHosts, 0, min($numSeeds, count($seedHosts)));
// Connect to $numSeeds peers
/** @var Peer[] $vNetAddr */
$vNetAddr = [];
foreach ($seeds as $seed) {
echo " [ query DNS seed: " . $seed . " ] \n";
$this->dns->resolve($seed)->then(function ($ipList) use(&$vNetAddr, $peerList, &$numSeeds) {
$vNetAddr[] = $ipList;
if (count($vNetAddr) == $numSeeds) {
$peerList->resolve($vNetAddr);
}
});
}
// Compile the list of lists of peers into $this->knownAddresses
return $peerList->promise()->then(function (array $vPeerVAddrs) {
shuffle($vPeerVAddrs);
/** @var NetworkAddressInterface[] $addresses */
$addresses = [];
array_map(function (array $value) use(&$addresses) {
foreach ($value as $ip) {
$addresses[] = new NetworkAddress(Buffer::hex('01', 8), $ip, 8333);
}
}, $vPeerVAddrs);
$this->knownAddresses = array_merge($this->knownAddresses, $addresses);
return $this;
});
}
示例10: go
/** @internal */
public function go(Process $process)
{
$this->deferred = $deferred = new Deferred();
$this->process = $process;
$buffered = null;
$process->stdout->on('data', function ($data) use(&$buffered) {
if ($data !== '') {
$buffered .= $data;
}
});
$process->on('exit', function ($code) use($deferred) {
if ($code !== 0) {
$deferred->reject($code);
} else {
$deferred->resolve();
}
});
$that = $this;
$this->promise = $deferred->promise()->then(function () use(&$buffered, $that) {
if ($buffered === null) {
$buffered = true;
} else {
$buffered = $that->parseValue(trim($buffered));
}
return $buffered;
});
}
示例11: createInternalAsync
protected function createInternalAsync($host, $docroot, $router)
{
$deferred = new Deferred();
$process = new BuiltinServer($host, $docroot, $router, $this->php);
$process->start($this->loop);
$process->on('exit', function ($code) use($deferred) {
$this->stderr->write("Process exit with code {$code}\n");
$deferred->reject();
});
$process->stdin->close();
$process->stdout->close();
$process->stderr->on('data', function ($output) use($deferred) {
$this->stderr->write($output);
$deferred->reject();
});
$timer = new Deferred();
$this->loop->addTimer(0.05, function () use($timer, $process) {
if (DIRECTORY_SEPARATOR === '\\') {
// Pipes opened by proc_open() can break stream_select() loop in Windows.
// This fix might do the trick...
$process->stderr->close();
}
$timer->resolve($process);
});
return \React\Promise\race([$deferred->promise(), $timer->promise()])->then(null, function () use($process) {
$process->terminate();
return new RejectedPromise();
});
}
示例12: testThrowsWhenAccessingInvalidProperty
/**
* @expectedException \RuntimeException
*/
public function testThrowsWhenAccessingInvalidProperty()
{
$deferred = new Deferred();
$f = new FutureArray($deferred->promise(), function () {
});
$f->foo;
}
示例13: call
/**
* @param $channel
* @param string $message
* @return DeferredPromise
*/
public function call($channel, $message)
{
$loop = LoopFactory::create();
$factory = new StompFactory($loop);
$client = $factory->createClient();
$deferred = new Deferred();
$timer = $loop->addTimer(2, function () use($deferred, $client) {
$client->disconnect();
$deferred->reject(new RpcTimeIsOutException());
});
$client->connect()->then(function (StompClient $client) use($message, $channel, $loop, $deferred, $timer) {
$rpcReceiver = function (Frame $frame) use($deferred, $timer, $client) {
$timer->cancel();
$client->disconnect();
try {
$deferred->resolve($frame);
} catch (\Exception $e) {
$deferred->reject($e);
}
};
$client->sendToTemp($channel, $message, [], $rpcReceiver);
}, function () use($deferred, $client) {
$client->disconnect();
$deferred->reject(new \RuntimeException('Error start rpc connection'));
});
$loop->run();
return $deferred->promise();
}
示例14: show
/**
* @returns \React\Promise\Promise
*/
public function show()
{
$deferred = new Deferred();
$this->io->out('hello');
$deferred->reject(false);
return $deferred->promise();
}
示例15: doQuery
public function doQuery($nameserver, $transport, $queryData, $name)
{
$parser = $this->parser;
$loop = $this->loop;
$response = new Message();
$deferred = new Deferred();
$retryWithTcp = function () use($nameserver, $queryData, $name) {
return $this->doQuery($nameserver, 'tcp', $queryData, $name);
};
$timer = $this->loop->addTimer($this->timeout, function () use(&$conn, $name, $deferred) {
$conn->close();
$deferred->reject(new TimeoutException(sprintf("DNS query for %s timed out", $name)));
});
$conn = $this->createConnection($nameserver, $transport);
$conn->on('data', function ($data) use($retryWithTcp, $conn, $parser, $response, $transport, $deferred, $timer) {
$responseReady = $parser->parseChunk($data, $response);
if (!$responseReady) {
return;
}
$timer->cancel();
if ($response->header->isTruncated()) {
if ('tcp' === $transport) {
$deferred->reject(new BadServerException('The server set the truncated bit although we issued a TCP request'));
} else {
$conn->end();
$deferred->resolve($retryWithTcp());
}
return;
}
$conn->end();
$deferred->resolve($response);
});
$conn->write($queryData);
return $deferred->promise();
}