Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Amp Pattern Question #63

Closed
withinboredom opened this issue Jan 31, 2017 · 3 comments
Closed

Amp Pattern Question #63

withinboredom opened this issue Jan 31, 2017 · 3 comments
Labels

Comments

@withinboredom
Copy link

I'm rewriting a db driver to use Amp 1.x in Aerys. It's pretty straight forward, except that I hit a wall with how promises are implemented. Here's some example code that shows my issue:

function connect($options) {
  /* connect */
  Amp\onReadable($socket, function($watcherId) {
    /* read data */
    $inFlight[$token]->succeed($data); // $inFlight[$token] is the matching request for this query
}

function query($query) {
  /* Send query */
  $inFlight[$token] = new Amp\deferred();
  $promise = $inFlight[$token]->promise();
  return $promise->when(function($error, $data) use (/*lots of stuff from query send*/) {
    /* transform $data into native objects */
  }
}

function myCoRoutine() {
  $data = yield query($query);
}

However, $data in myCoRoutine holds the results of the original response from the server, before being transformed. Do you have any tips on how to get the result from the when in the query() function, instead of from the watcher?

@kelunik
Copy link
Member

kelunik commented Jan 31, 2017

when doesn't work like then, it doesn't transform any value, it's a pure consumer. We know, it's strange that it's a fluent interface, we removed that in Amp v2.

You can either use Amp\pipe or a coroutine to transform the value:

<?php

function query($query) {
  /* Send query */
  $inFlight[$token] = new Amp\Deferred;
  return Amp\pipe($inFlight[$token]->promise(), function($data) use (...) {
    return ...;
  }
}
<?php

function query($query) {
  return Amp\resolve(function () use ($query) {
    $result = yield rawQuery(...);
    return transformRawQuery($result);
  });
}

@withinboredom
Copy link
Author

Thanks for the quick response! Works like a charm.

@bwoebi
Copy link
Member

bwoebi commented Jan 31, 2017

Awesome! // closing as resolved.

@bwoebi bwoebi closed this as completed Jan 31, 2017
kelunik pushed a commit that referenced this issue Mar 10, 2017
kelunik pushed a commit that referenced this issue Mar 10, 2017
…tcher"

This reverts commit 5bd7794, reversing
changes made to 6449495.

Revert too quick merge (sorry) as per #58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

3 participants