Trying to learn how to work with Promises and Async. I can send an object to a module but for some reason I continue to get an undefined when processing the return. I've narrowed it down to either my return on my module is incorrect or I'm coding something wrong on my Async.
main.js
ipcMain.on('file-object', (e, res) => {
module.exports.res = res
console.log('Starting main.js')
async function findTest() {
const testResult = await valid.jsonTest()
console.log(testResult)
mainWindow.webContents.send('test-results', testResult)
}
findTest()
})
foobar.js
module.exports = {
jsonTest: function() {
let testPromise = new Promise((resolve) => {
child = exec('/usr/bin/java -jar ' + jarFile + ' ' + res.res.path, function(error, stdout, stderr) {
if (stderr !== "") {
resolve(
resultArray = {
"status": "error",
"response": stderr
}
)
} else {
resolve(stdout)
}
})
})
testPromise.then((successMessage) => {
console.log(JSON.stringify(successMessage))
return successMessage
})
}
}
After searching and reading several Q&As I've also tried:
let foobar = valid.jsonTest()
waitForElement()
function waitForElement() {
if (typeof foobar !== 'undefined') {
console.log('Getting results')
console.log(foobar)
mainWindow.webContents.send('test-results', foobar)
return
}
else {
console.log(foobar)
setTimeout(waitForElement, 1000)
}
}
but I get a continuous undefined which is why I think I might be incorrectly returning the module. Also tried:
let validationMessage = valid.jsonTest()
console.log("Starting main.js")
let resultPromise = () => {
return new Promise((resolve) => {
console.log('entering promise')
resolve()
console.log(`Status results: ${status}`)
})
}
Promise.resolve().then(() => resultPromise(
console.log(validationMessage.status)
))
Research references from my quieres:
- node.js call external exe and wait for output
- What is the purpose of Node.js module.exports and how do you use it?
- Best way to return an exported module
- How to make a function wait until a callback has been called using node.js
- How to return data from promise
- Export Cookie Jar to JSON with Node Request
- node.js call external exe and wait for output
- node.js resolve promise and return value
How can I send an object to a file, process that object, return and get the result because I'm missing something here and I do not understand why I get undefined and my Promise continues.