Getting the results for TextBuffer.scan


Firstly, i’m relatively new to JS, so bear with me.

I want to build an index of a (markdown) document by scanning for headings and building a tree structure of them. I was planning to use TextBuffer::scan(regex, callback) . However I need to collect the results of the scan into a data structure outside of the call. I was going to do:

    let h1List = []

    textBuffer.scan(/(^#)(.*)/, (scanResult) => {
      // match, matchText, range, stop, replace)
      let hBlock = {};
      hBlock.start = scanResult.range.start;
      hBlock.headingRange = scanResult.range;


But as far as I understand there’s no guarantee that h1List will be filled by the time I get to console.log . I would like to know how to do this - I’ve started exploring es6 generators/iterators (I’m wrting my plugin with babel support) with the idea that should help but I’m not getting anywhere


TextBuffer.scan is designed for doing search and replace functionality on the data in the file. What you’re describing here:

isn’t searching but parsing. You should take a look at the various available Markdown parsers such as marked for example.


I looked at those already and they don’t really help much - they aren’t especially designed to create hierarchical documents. I also want to make use of the buffer positions returned by scan to mark the corresponding regions of text. I would actually prefer to iterate over the applied scopes, but apparently there isn’t an API for that yet.

In any case, the general JS question (whether using scan or other async API) is how to get a list of values from a callback. So in general when you have

asyncCall(arg, callback(results))

how to collect the results?