# JavaScript API Why does client.search method always execute last?

**URL:** <https://discuss.elastic.co/t/javascript-api-why-does-client-search-method-always-execute-last/50900>\
**Category:** Elasticsearch\
**Created:** [May 25, 2016, 4:16am UTC](https://discuss.elastic.co/t/javascript-api-why-does-client-search-method-always-execute-last/50900 "2016-05-25T04:16:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ngmgithub](https://avatars.discourse-cdn.com/v4/letter/n/bcef8e/32.png) [@ngmgithub](https://discuss.elastic.co/u/ngmgithub)\
**Post date:** [May 25, 2016, 4:16am UTC](https://discuss.elastic.co/t/javascript-api-why-does-client-search-method-always-execute-last/50900/1 "2016-05-25T04:16:53Z")

</div>

I'm using the `client.search` method very similar to the example with the `.then` in it. For some reason, it seems to always execute after all other operations in my code (save some global variable declarations at the start) that come after the client.search method, even if I put in a delay between them (to rule out any asynchronous race conditions).

1. Invoke the `client.search` method
2. (optionally add a `sleep.sleep(10);` delay which hasn't helped)
3. Handle or `console.log(outputFromClientSearch)`

Putting the delay between steps 1 and 3 results in things executing in the order of 2 -\> 3 -\> 1. Without the delay this executes 3 -\> 1.

The only way to print or handle the output from the `client.search` method is within it, generally within the `.then` section. I have also tried encapsulating 1, 2 and 3 in functions and calling them in sequential order, still they execute in the same incorrect sequence. This greatly limits what can be done from a handling standpoint on the results of a query.

Is there a way to ensure the order of operations here?

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:49pm UTC](https://discuss.elastic.co/t/javascript-api-why-does-client-search-method-always-execute-last/50900/2 "2017-07-05T22:49:16Z")

</div>

Closed on July 5, 2017, 10:49pm UTC


