0

Actually I have tried one code. This code is working fine but I want to access this information outside of callback function. But i am unable to find solution.

var prompt = require('prompt');

  prompt.start();

  prompt.get(['username', 'email'], function (err, result) {

    console.log('Command-line input received:');
    console.log('  username: ' + result.username);
    console.log('  email: ' + result.email);

    data = result.username;
  });

console.log(data);

Here if i'm trying to retrieve print data variable it show's error.

Admins-MacBook-Pro:Basic node programs Sandeep$ node Node3.js 
prompt: username:  /Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22
console.log(data);
            ^

ReferenceError: data is not defined
    at Object.<anonymous> (/Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22:13)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
  • Try putting the console.log in the callback (so directly after you give `data` a value) – gandreadis Jan 06 '18 at 09:30
  • I have already three console.log() in callbacks. It is working fine but i want to access user entered quantity outside of callback. It's not working. – Er. Sandeep Pal Jan 06 '18 at 09:35

2 Answers2

1

"You won't be able to access that variable outside the callback function. The reason is, the Node.js has a special feature of passing a callback function as the next block of code to be executed after performing an asynchronous IO task."

Refer to this one: how can find return variable value outside anonymous function in node js mysql query function

You can also check this link to learn how to handle with async flow: http://book.mixu.net/node/ch7.html

M.Soyturk
  • 340
  • 3
  • 14
1

You could use promise, check docs about promise and newer es 6 Async/ await. With promise you could use something like this:

var prompt = require('prompt');

function getPromt () {  return new Promise( (resolve, recect) => {
   prompt.start();

   prompt.get(['username', 'email'], function (err, result) {
    console.log('Command-line input received:');
    console.log('  username: ' + result.username);
    console.log('  email: ' + result.email);
    resolve( result.username);
    });
  });
}
getPromt().then(data =>
console.log('After promise ' + data), ()=>{});
MRsa
  • 666
  • 4
  • 8