0

Noob in nodejs here and still trying to learn how nodejs works. Could you please let me know how can I pass the callback response from "getDatafromCosmosDB" function into a variable in the main function and print those values.

When I try to assign getDatafromCosmosDB to a variable "respdata" and try to print it, it is not working.

async function main(params, callback) {
    const logger = Core.Logger('main2', { level: params.LOG_LEVEL || 'info' })
    try {
        logger.info('main action')
        const respdata = getDatafromCosmosDB(function(response){
            console.debug(response)
            return response
        });
         console.debug(respdata)
    } catch (e) {
        console.debug(e)
    }
}

exports.main = main
async function getDatafromCosmosDB(callback){
    var query = new azure.TableQuery()
    .top(5)
    tableService.queryEntities('myCosmosTable', query, null, function (error, result, response) {
        if (!error) {
            console.log('success')
            return callback(result.entries)
        }
    });
}
Scorpyon
  • 226
  • 3
  • 4
  • 9
  • 2
    Does this answer your question? [nodeJs callbacks simple example](https://stackoverflow.com/questions/19739755/nodejs-callbacks-simple-example) – yeya May 10 '21 at 14:28
  • That helps quite a bit, thank you. I was also looking for some examples as well and below answer helps as well! – Scorpyon May 26 '21 at 05:29

1 Answers1

1

Try something like this,

import {
  createTableService,
  services,
  ServiceResponse,
  TableQuery
} from 'azure-storage';

getDatafromCosmosDB(): Promise<ServiceResponse> {
 return new Promise(async (resolve, reject) => {
       this.tableService.queryEntities(
        this.tableName,
        query,
        null,
        (error, _, response) => {
          if (!error) {
            resolve(response);
          } else {
            reject(error);
          }
        }
      );
    });
}

and invoke like,

this.getDatafromCosmosDB().then(data => {
  console.log(data);
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396