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

Chaining question #24

Closed
ghost opened this issue Dec 3, 2014 · 3 comments
Closed

Chaining question #24

ghost opened this issue Dec 3, 2014 · 3 comments
Labels

Comments

@ghost
Copy link

ghost commented Dec 3, 2014

I have an array of items of variable length where I want to process each item by the same function after the previous promise has resolved. I just can't figure out how to code it, I keep ending up thinking in loops while I guess I shouldn't:

$items = array(...variable number of items in here...);

$this->doSomethingAsyncAndReturnAPromise($firstItem)->then(
    function () {
        $this->doSomethingAsyncAndReturnAPromise($secondItem)->then(     
            ... and so on for all the remaining $items
        );
    }
);

Can anyone point me in the right direction how to do this?

@jsor
Copy link
Member

jsor commented Dec 3, 2014

You can use React\Promise\reduce if you want to run the tasks in sequence with no overlap:

React\Promise\reduce($items, [$this, 'doSomethingAsyncAndReturnAPromise'])->then(function() {
    echo "All done";
});

If they can run in parallel, use React\Promise\map:

React\Promise\map($items, [$this, 'doSomethingAsyncAndReturnAPromise'])->then(function() {
    echo "All done";
});

@ghost
Copy link
Author

ghost commented Dec 3, 2014

Great info, I was looking for use cases for these two functions already. It was not very clear to me from the documentation how to use them.

Many thanks, reduce() it is.

@ghost ghost closed this as completed Dec 3, 2014
@jsor
Copy link
Member

jsor commented Dec 3, 2014

They both work exactly like PHP's array_map and array_reduce with the addition that the values of the input array can be promises and the callbacks can return promises.

In this case, we're "abusing" reduce() for your use case. Since the callback must receive the return value of the previous iteration, reduce() takes care of running in sequence.

@clue clue added the question label Jun 9, 2022
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants