在express.js应用程序中,我有2个模块:
第一个是初始化模块,我在第二个开始时调用它;主模块。
mainModule.js
const result = require('initilalizerModule')
...
initilalizerModule.js:
const soap = require('soap');
const path = require('path');
//passed en params for DAO
const endpoint = 'https://myurl.com';
const url = path.resolve(__dirname, 'mycontract.wsdl');
const soapOptions = {
forceSoap12Headers: true,
connection: 'keep-alive',
disableCache: false
};
function initialize() {
console.log("test")
return new Promise((resolve,reject) => {
soap.createClient(url, soapOptions, function (err, RESULT) {
if (err) {
reject('err');
}
else {
client.setEndpoint(endpoint);
resolve(RESULT);
}
});
})
}
module.exports = {
myResult : ....
}
我有这种异步initialize()
方法,它带来了RESULT
我的目的是如何从我的RESULT
导出此initilizerModule
对象以在我的mainModule
之后使用?
答案 0 :(得分:2)
您必须了解异步编程。 require是同步的,默认情况下已缓存。某些任务异步后您要执行的任何操作。您必须使用回调。这是一个基本示例。
// main.js
const {init} = require("./provider")
init((data) => {
console.log(data) // somedata
})
// provider.js
const someDelay = () => new Promise(r => {
setTimeout(() => r("somedata"), 1000)
})
exports.init = (cb) => {
someDelay().then(cb)
}
如果您使用的是最新的node.js。您可以使用async / await。 异步/等待版本
// main.js
const {init} = require("./provider")
async function start() {
const data = await init()
console.log(data) // somedata
}
start()
// provider.js
const someDelay = () => new Promise(r => {
setTimeout(() => r("somedata"), 1000)
})
exports.init = async () => {
return await someDelay()
}
希望这会回答您的问题!干杯。
答案 1 :(得分:0)
快速浏览一下,您可以将initialize()
函数定义为变量,然后将其导出,例如const myResult = function initialize() {...
然后使用
module.exports = { myResult }