Through recent advancements in the new standards, there are a couple of handy approaches that can help when you are working with JavaScript. First and foremost, the newly released SDK is promise based. The main reason behind this was to avoid any potential ‘callback hells’ and the whole concept ties in perfectly with the usually asynchronous nature of such functionalities in JavaScript environments. This means that a Node JS version of at least 6.4.0 is required, or if you have any kind of limitations with upgrading the Node JS, then you could use a JS transpiler (or Typescript).

Here are some examples showcasing the new promise based library.

const er = new EventRegistry({apiKey: "YOUR_API_KEY"});

er.getConceptUri("Star Wars")
  .then((conceptUri) => {      
    # create a query where we will search for the concept Star Wars
    const query = new QueryEvents({ conceptUri: conceptUri });    
    
    # as a result we want to obtain a list of events, sorted by date
    # limit the output to 10 events
    const requestEventsInfo = new RequestEventsInfo(
      {sortBy: "date", count: 10});         
    query.addRequestedResult(requestEventsInfo);      
    return er.execQuery(query); 
  }).then((response) => {      
    # print the returned list of events
    console.info(response); 
  });

An alternative approach using the new “async/await” pattern.

const er = new EventRegistry({apiKey: "YOUR_API_KEY"}); 

async function iterateOverEvents() { 
  const query = new QueryEvents({
    conceptUri: await er.getConceptUri("Star Wars")}); 
    const requestEventsInfo = new RequestEventsInfo(
      {sortBy: "date", count: 10});    
    query.addRequestedResult(requestEventsInfo); 
    return er.execQuery(query); 
} 
iterateOverEvents();

To reiterate, almost all the library functions return a promise, which then resolves with either the corresponding data from the specified server or with an error message. Notable exceptions are the following classes: QueryArticlesIter, QueryEventArticlesIter and QueryEventsIter. They provide a way to gradually fetch and process the data from the server.

These classes provide their own implementation of the execQuery() function which differs from the main implementation. It accepts 2 arguments. First argument is an anonymous function which is called every time we fetch a new batch of events or articles. The second is a function that is called when we finish our iteration.

Example: Iterate over all articles that belong to a particular event with a given URI.

const er = new EventRegistry(); 

# create iterator that will return articles in the given event
const iter = new QueryEventArticlesIter(er, "eng-2940883"); 
iter.execQuery((articles) => { 
  console.info(articles); 
}, () => { 
  console.info("done"); 
});

Detailed examples can be found on GitHub and library documentation can be found on the project’s wiki pages.