2017-07-26 261 views
1

我再次破壞b *** s ... 我很抱歉不得不回到你們,但我覺得網上提供的信息很混亂,似乎無法找到適合我的問題的答案。 所以如果你們中的一個嚮導/神的幫助我,我會非常感激。NodeJS異步/等待輸出變量

我試圖導出一個變量,從承諾產生一個不同的模塊。 這裏是我的代碼:

主要:

//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() 

,並承諾該模塊:

//module.js 

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

module.exports = { 
    somePromise1, 
} 

正如你可以看到somePromise1,其實是一樣的somePromise2但在不同的模塊。事情是,我顯然似乎無法得到要導出的味精變量,它會產生一個未定義的(如果我在本地執行所有操作:在同一個文件中,它可以毫無用處地工作)。

在此先感謝您的幫助,並提前對不起,如果您發現這是一個現有問題的副本... I'crawled SO自昨天起回答並移動代碼,但似乎沒有任何適用。 。

+1

您沒有導出'msg'變量。你只是出口'somePromise1'的承諾。 –

回答

2

你在導入一個錯誤,並在使用該承諾的錯誤:

//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() 
+0

它的工作!可以幫助我多一點與誰的?我的意思是,爲什麼我需要添加'.somePromise1'而不是隻指定'./module'? – Ardzii

+1

對不起,非常感謝! (btw) – Ardzii

+1

@Ardzii我建議你閱讀一篇關於導入/導出的好文章:https://www.sitepoint.com/understanding-module-exports-exports-node-js/ –