1

Me again busting b***s ... I'm sorry to have to come back to you guys, but I find the information available online very confusing and can't seem to find an appropriate answer to my problem. So if one of you wizards/gods of the Node could help me, I'd greatly appreciate it.

I'm trying to export a variable that yields from a promise to a different module. Here's my code:

The main:

//app.js <--- This is where I need the variable exported.

var sp1 = require('./module');

var somePromise2 = new Promise((resolve, reject) => {
  resolve('Hey! It worked the second time!');
});


async function exec() {
  const message1 = await sp1.msg
  const message2 = await somePromise2
  console.log('Success', message1, message2);
}

exec()

and the module with the promise:

//module.js

var somePromise1 = new Promise((resolve, reject) => {
  var msg = '';
  resolve(msg = 'Hey! It worked!');
});

module.exports = {
  somePromise1,
}

As you can see the somePromise1, is actually the same as somePromise2 but in a different module. Thing is, I apparently can't seem to get the msg variable to be exported, it yields an undefined (if I do everything locally: in the same file, it works seemlessly).

Thanks in advance for your help and sorry in advance if you find this is a duplicate of an existing question... I'crawled SO since yesterday for an answer and moved the code around but nothing seems to apply...

Martin Carre
  • 1,157
  • 4
  • 20
  • 42

1 Answers1

2

You have an error in importing and a mistake in using the promise:

//app.js <--- This is where I need the variable exported.

var sp1 = require('./module').somePromise1;

var somePromise2 = new Promise((resolve, reject) => {
  resolve('Hey! It worked the second time!');
});


async function exec() {
  const message1 = await sp1; 
  const message2 = await somePromise2;
  console.log('Success', message1, message2);
}

exec()
stdob--
  • 28,222
  • 5
  • 58
  • 73