0

I tried one simple function in node js and pass data to one file on to another file.but its throwing undefined.how to solve it in node js

fun.js

function Get_Value()
{
    client.get('products', function(err,results) {
        return results

    })
    console.log(results)
}

I tried to print value in outside the function but its print undefined how to print result in out side function

smith hari
  • 437
  • 1
  • 11
  • 22

3 Answers3

0
async function Get_Value() {
  let results = await new Promise(function(resolve) {
    client.get("products", function(err, results) {
      resolve(results);
    });
  });

  console.log(results);
}

SIMDD
  • 615
  • 5
  • 15
0

This is very easy using async/await features provided by ES7.

async function  Get_Value()
{
    const results = await new Promise((resolve, reject) => {
                        client.get('products', function(err,results) {
                             resolve(results);
                        })
                    });
     console.log(results);  
 }
narayansharma91
  • 2,273
  • 1
  • 12
  • 20
0

Define your Get_Value to take a callback function. You then pass a callback when you're invoking Get_Value:

function Get_Value(callback) {
  client.get('products', function(err,results) {
    if (err) return callback(err)
    callback(null, results);
  })
}

function mycallback(err, data) {
  if (err) {
    // handle error
    console.error(err)
  } else {
    console.log(data);
  }
}
Get_Value(mycallback)
1565986223
  • 6,420
  • 2
  • 20
  • 33