function not returning JSON property value - node.js

function not returning JSON property value - node.js

By : AIM
Date : November 22 2020, 03:01 PM
hope this fix your issue You need to return the promise from sendDB(). Currently there is no return to the outer function.
Since the promise is asynchronous you need to use then() chained to the function call
code :
function sendDB() {
   // return the promise
   return couch.get(dbName, viewUrl).then(
        function(data, headers, status){
            DB = JSON.stringify(data.data.rows[0].value.name);
            return DB;

Share : facebook icon twitter icon
Node.JS Lambda Function Not Returning JSON

Node.JS Lambda Function Not Returning JSON

By : overt
Date : March 29 2020, 07:55 AM
Does that help I am not familiar with AWS, but base on http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html, following code may work.
code :
exports.handler = function (event, context, callback) {
    console.log("Request received:\n", JSON.stringify(event));

    var mysql = require('mysql');

    var jsonconnection = mysql.createConnection({
        host: 'servername',
        user: 'username',
        password: 'password',
        database: 'database'

    // Move applicant_data outside of query as it will be needed at the end in callback
    var applicant_data = {};

    console.log('Connected to MySQL:');

    jsonconnection.query('SELECT applicant_id FROM customers WHERE applicant_id = \'' + event.applicant_id + '\'',
        function (err, res) {
            if (err) throw err;

            console.log('Row Details:', JSON.stringify(res));
            applicant_data = {
                // Only use first row of data
                applicant_id: res[0].applicant_id;


    // Move connection end out side of query

    // This should return your data, in JSON form
    callback(null, JSON.stringify(applicant_data));

    // I assume this is the correct use for succeed
JSON node in node js Uncaught TypeError: Cannot read property 'Cube' of undefined

JSON node in node js Uncaught TypeError: Cannot read property 'Cube' of undefined

By : Adrian
Date : March 29 2020, 07:55 AM
it helps some times I'm trying to read the value of Currency of every country and their respective values from this JSON in node.js but every time i read the values i get this error. Can somebody point me to right way of reading key value pairs of nested JSON structure? , Replace your following line:
code :
var Currency = parsedResponse.gesmes.Cube[0][1][0].currency;
var Currency = parsedResponse['gesmes:Envelope']['Cube'][0]['Cube'][0]['Cube'][0]['$'].currency;
mule org.json.JSONObject returning property value as null though the json property does have value for it

mule org.json.JSONObject returning property value as null though the json property does have value for it

By : Peter
Date : March 29 2020, 07:55 AM
I hope this helps you . I have figured out the current issue. if there is any logger added to fetch the properties from the payload right after the expression component then its screwing up further. if you just remove the logger that was added after the expression component then after json to object conversion, i am able to fetch the values. that solves the current issue. but i would like to understand the difference between fetching the properties #[payload.con_id] vs #[payload.'con_id']. i can start a separate conversation for the same.
Node Function not returning JSON object

Node Function not returning JSON object

By : Pradeep Rama
Date : March 29 2020, 07:55 AM
like below fixes the issue It is becuase cognitoExpress.validate is an async operation. it will run and the callback of this function will run. But by the time this all happens. Your following line
console.log(auth); gets hit already and you see undefined becuase you are actually not returning anything from verifyToken method at that time.
code :
const CognitoExpress = require("cognito-express");

//Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress({
    cognitoUserPoolId: process.env.USER_POOL_ID, // User Pool id (created via Console->Cognito Manage User Pool)
    region: process.env.REGION, //User Pool Region
    tokenUse: "id", //Possible Values: access | id
    tokenExpiration: 3600000 //Up to default expiration of 1 hour (3600000 ms)

//Our middleware that authenticates all APIs under our 'authenticatedRoute' Router
module.exports = function(){
    this.verifyToken=(function(token, req, res) {
        return new Promise(function(resolve, reject) {
          //I'm passing in the id token in header under key Token
          let TokenFromClient = token;

          //Fail if token not present in header. 
          if (!TokenFromClient) return "Token missing from header";

          cognitoExpress.validate(TokenFromClient, function(err, response) {

              //If API is not authenticated, Return 401 with error message. 
              if (err)  {
              } else {
                //Else API has been authenticated. Proceed.

var verify_tokenController = {};

//Verify AWS token recieved through client header by calling verifyToken Library function
verify_tokenController.verify = function(req, res) {

    //Import verifyToken Library function

    verifyToken(req.header('Token'), req, res)
        console.log(resposne, 'response')
        res.send({success:true, msg:"Token Authenication result", result: response});    
      .catch(function(err) {
        res.send({success:false, msg:"Token Authenication Error", Error:err});

module.exports = verify_tokenController;
Javascript/Node/Express: res.json needs to wait for a function to finish running before returning... but res.json is imp

Javascript/Node/Express: res.json needs to wait for a function to finish running before returning... but res.json is imp

By : user3319969
Date : March 29 2020, 07:55 AM
I wish did fix the issue. The above code executes synchronously, therefore you return in the same frame before any promise has the chance to resolve.
We can clean the above code up as follows:
code :
module.exports = app => {

  app.get("/api/seMapServerStatus", (req, res) => {
    const ports = ["27111", "27112", "27117", "27118", "27119", "27110", "27115", "27116", "27113", "27114"]

    function hitServers(port) {
      return Gamedig.query({
        type: "aGameType",
        host: "theServer'sIP",
        port: port

    // With error handling
    function hitServersSafe(port) {
      return hitServers(port)
        .then(result => {
          return {
            success: true,
            result: result
        .catch(error => {
          return {
            success: false,
             // you probably need to serialize error
            error: error

    const promises = ports.map(port => hitServers(port))
    // With error handling
    // const promises = ports.map(port => hitServersSafe(port))

      .then(data => res.json(data))
      .catch(error => {
        // do something with error

Related Posts Related Posts :
  • How to have multiple Flatlists with filtered data in React Native
  • Scroll to Top of Document After Param Change in Angular 4?
  • Sweetalert2 Ajax - post input data
  • Can I build a split slider using slick?
  • How can I customize a permission request popup for push notifications in a browser?
  • Find array in another array and get index of result
  • Service worker promise.then is not defined
  • how to keep validation off if some section of forms not showing during form-filling in jquery
  • Store string values to array inside a loop
  • How can I search through this JS object?
  • Accordion close animation not working. It opens (with animation) and closes (with no animation)
  • Mocha, nodejs promise test can't finish because lack of done
  • No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefor
  • delete certain parts of a text text in javascript
  • Angular 2 D3 tree is not rendering correctly
  • Update selected item from Flatlist in Firebase using React Native
  • Trouble understanding Javascript closure example
  • edit canvas pixel coordinates
  • Insert script into a script
  • Axios is returning a string called "Array" instead of an object
  • How to submit forms with QuillJs and body-parser?
  • Design pattern for sitewide configuration in Angular JS
  • firestore orderby on subproperty (subcollection)
  • How does angular method decorator work?
  • How do I pull from Google Analytics and create a trending threads section based on most popular content
  • Rails 5: JavaScript runs but doesn't appear in browser
  • Insert PHP functions into Javascript
  • want to make the revolution slider's height dynamic based on jQuery(window).height()
  • how can convert a base64 svg image to base64 image png
  • new table row is added under the first cell in the header
  • Why is AWS SQS so slow?
  • how to read a json config file and setting that parameter to ajax
  • object literal. Inexact type is incompatible with exact type (no object spread)
  • Define globals when bundling to umd or commonjs
  • How do I store functions with their parameters in an array and execute them sequentially?
  • Overcoming antialiasing on canvas lines for mouse event
  • Scrapy splash not returning results
  • how you random for xhouse
  • How to set a Slack Reminder with Slack Reminder API to a channel?
  • How to align title html div with chart horizontally in highchart?
  • Testing a redirect to a new route with Cypress
  • Get the first N properties of an Object using Underscore Map
  • How to specify proptypes to allow nullable, required prop value?
  • scaleQuantile function doesn't output what I expect
  • jQuery toggleClass() method not applying to JSON generated content
  • new Date() setMonth getMonth bug?
  • Incorrect date being set with new Date()
  • Is possible to download image by URL and get its local path in javascript?
  • NodeJS Unhandled Promise Rejection
  • Creating Reusable Helper Functions in React.js
  • Service worker error: event already responded to
  • flowhub/the-graph: React not defined error
  • Why this JavaScript includes() feature make sense?
  • Validating Duplicate Data Between ObservableArrays
  • Angular Route Always need slash if it's case insensitive
  • Change select box options upon selecting option in first select box
  • Javascript ES6 - Check if a Symbol is available in global registry without creating it
  • why does textbox.disabled= true clears the text of the textbox?
  • combine the two JSON Objects depending on the ids
  • Vue Webpack & PapaParse
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org