NodeJS Async/Await 导出变量
NodeJS Async/Await Exporting a Variable
我又在捣蛋了……
很抱歉不得不回到你们身边,但我发现网上提供的信息非常混乱,似乎无法找到适合我的问题的答案。
因此,如果 Node 的 wizards/gods 中的一位可以帮助我,我将不胜感激。
我正在尝试将一个从 promise 产生的变量导出到另一个模块。
这是我的代码:
主要:
//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()
和带有 promise 的模块:
//module.js
var somePromise1 = new Promise((resolve, reject) => {
var msg = '';
resolve(msg = 'Hey! It worked!');
});
module.exports = {
somePromise1,
}
如您所见,somePromise1 实际上与 somePromise2 相同,但在不同的模块中。事情是,我显然无法导出 msg 变量,它会产生一个未定义的(如果我在本地做所有事情:在同一个文件中,它会无缝地工作)。
提前感谢您的帮助,如果您发现这与现有问题重复,请提前致歉...
从昨天开始,我一直在抓取答案并移动了代码,但似乎没有任何应用...
你导入错误,使用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()
我又在捣蛋了…… 很抱歉不得不回到你们身边,但我发现网上提供的信息非常混乱,似乎无法找到适合我的问题的答案。 因此,如果 Node 的 wizards/gods 中的一位可以帮助我,我将不胜感激。
我正在尝试将一个从 promise 产生的变量导出到另一个模块。 这是我的代码:
主要:
//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()
和带有 promise 的模块:
//module.js
var somePromise1 = new Promise((resolve, reject) => {
var msg = '';
resolve(msg = 'Hey! It worked!');
});
module.exports = {
somePromise1,
}
如您所见,somePromise1 实际上与 somePromise2 相同,但在不同的模块中。事情是,我显然无法导出 msg 变量,它会产生一个未定义的(如果我在本地做所有事情:在同一个文件中,它会无缝地工作)。
提前感谢您的帮助,如果您发现这与现有问题重复,请提前致歉... 从昨天开始,我一直在抓取答案并移动了代码,但似乎没有任何应用...
你导入错误,使用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()