nad
nad

Reputation: 2850

node.js: how to make asynchronous data available globally

I am new to Node.js. I am using DynamoDB local to read data from a database as below.

function readFromTable (params){

  docClient.get(params, function(err, data) {
      if (err) {
          console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));

      } else {
          console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
          result = JSON.stringify(data, null, 2);
          console.log ("got result");
          console.log (result);
      }
  });

I understand that it is an asynchronous function and can't return. Asynchronous data is only available inside the function success event.

But I need to make the result data available outside the function as I need to return it to an html. How do I do that?

Upvotes: 1

Views: 79

Answers (2)

itsundefined
itsundefined

Reputation: 1450

For your case I would recommend using promises. Here is your code.

function readFromTable(params) {
  return new Promise((resolve, reject) => {
    docClient.get(params, function(err, data) {
      if (err) {
          console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
          return reject(err);
      } else {
          console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
          result = JSON.stringify(data, null, 2);
          console.log ("got result");
          return resolve(result);
      }
    });
  });
}

readFromTable(yourParams).then((results) => {
  console.log('You got your results');
});

Upvotes: 2

Mathias Gheno
Mathias Gheno

Reputation: 787

the answer is callback or promises. Every variable can be accessed inside the function 'docClient'. Consider the simple example in callback:

function readFromTable (params) {

    function anotherFunction(callback) {
        //do something
        var someVariable = '';
        callback(someVariable);
    }

    docClient.get(params, function (err, data) {
        if (err) {
            console.log(err);
        } else {
            anotherFunction(function (someVariable) {
                console.log(someVariable);
                // you can access data here;
                console.log(data);
            })
        }
    })
};  

I hope I have helped.

Upvotes: 1

Related Questions