# Executing TextSearchInit multiple times

**URL:** <https://pdfjs.community/t/executing-textsearchinit-multiple-times/712>\
**Category:** Technical Support\
**Created:** [April 20, 2021, 4:57pm UTC](https://pdfjs.community/t/executing-textsearchinit-multiple-times/712 "2021-04-20T16:57:21Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![Logan](https://yyz1.discourse-cdn.com/flex031/user_avatar/pdfjs.community/logan/32/13_2.png) [@Logan](https://pdfjs.community/u/Logan)\
**Post date:** [April 27, 2021, 2:28pm UTC](https://pdfjs.community/t/executing-textsearchinit-multiple-times/712/6 "2021-04-27T14:28:54Z")

</div>

Hey there,

I tried a more realistic test case and now I can reproduce this issue. I believe this is due to the JS feature where callback functions are executed synchronously. `onDocumentEnd` is executed synchronously, and therefore the internal search state is not being reset before the next call to `textSearchInit`.

Refactoring the code to use a promise chain fixes the issue for me. (This is basically the same fix as your setTimeout, except a bit less “hacky”)

```javascript
    const queue = ['pdf', 'viewer'];

    function drawAnnotations() {
      if (queue && queue.length) {
        let chain = Promise.resolve();
        for (const nextAnnotation of queue) {
          chain = chain.then(() => {
            return drawAnnotation(nextAnnotation)
          })
        }
      }
    }
  
    function drawAnnotation(phrase) {
      return new Promise(resolve => {
        console.log('drawAnnotation(): ' + phrase);
      
        const searchMode = CoreControls.Search.Mode.HIGHLIGHT;
    
        const searchOptions = {
          fullSearch: true,
          onResult: (result) => {
            if (result.resultCode === CoreControls.Search.ResultCode.FOUND) {
              console.log('onResult: ' + result);
            }
          },
          onDocumentEnd: (result) => {
            resolve();
          }
        }
    
        docViewer.textSearchInit(phrase, searchMode, searchOptions);

      })

    }

    drawAnnotations();

```

Thanks!  
Logan

---

_[View the full topic](https://pdfjs.community/t/executing-textsearchinit-multiple-times/712)._
