1

I have looked around quite extensivly and could not find any example on how to use query results from the marklogic module inside node.js...

Most examples do a console.log() of results and thats it, but what if I need the query results (say in a JSON array and use these results later on?

Seems I am missing some node.js ascynch stuff here...

Example :

var marklogic = require('marklogic');
var my = require('./my-connection.js');

var db = marklogic.createDatabaseClient(my.connInfo);
var qb = marklogic.queryBuilder;

db.documents.query(
    qb.where(qb.parsedFrom('oslo'))
).result( function(results) {
  console.log(JSON.stringify(results, null, 2));
});

// I would like to use the results here
// console.log(JSON.stringify(results, null, 2))

Now question is I would like to use the results object later on in this script. I have tried using .then(), or passing it to a variable and returning that variable but no luck.

Regards,

hugo

Hugo Koopmans
  • 1,349
  • 1
  • 15
  • 27

1 Answers1

6

Simple answer: you need to continue your business logic from the result() callback.

In more detail, your goal is to do something with the result of an asynchronous computation or request. Since JS has no native async capabilities (such as threads), callbacks are typically used to resume an operation asynchronously. The most important thing to realize is that you cannot return the result of an async computation or request, but must resume control flow after it completes. Defining lots of functions can help make this kind of code easier to read and understand.

This example illustrates what's happening:

process.nextTick(function() {
  console.log('second')
})

console.log('first')

That program will log first, then second, because process.nextTick() asynchronously invokes the callback function provided to it (on the next turn of the event loop).

The answers at How do I get started with Node.js offer lots of resources to better understand async programming with node.js.

joemfb
  • 3,056
  • 20
  • 19