Hello I am a new coder and I saw this Electron helper to prompt for a value via input. https://github.com/p-sam/electron-prompt. I was wondering how I would store the value from user input. This is the code I have but I don't really understand how to pull out the data(user input) from the code to use. I would appreciate any help, thank you!
async function getStoreId()
{
prompt({
title: 'Get StoreId',
label: 'Store ID: ',
value: '',
inputAttrs: {
type: 'guid'
},
type: 'input'
})
.then((r) => {
if(r === null) {
console.log('user cancelled');
} else {
console.log('result', r);
//storeid = r;
}
})
.catch(console.error);
}
let storeid = await getStoreId;
console.log(storeid);
The prompt() function in the electron-prompt library returns a promise.
A promise can only be in one of three states:
Quite often, due to the sequential nature of Javascript, if you try and console.log() a promise before it has been fulfilled, you will receive a Promise { <pending> } message.
As you have wrapped your own function getStoreId() around the prompt() function (which returns a promise), you will not return anything unless you place a return statement in front of the prompt() function.
As a result, your getStoreId() function will now return the promise.
To handle the returned promise you must follow it up with a .then() method. The .then() method will then be processed when the promise is resolved (IE: It is no longer in the 'pending' state), meaning it has either been fulfilled or 'rejected'.
Inside the .then() method you can extract the result and either process it then and there or pass it on to another functions of yours for clearer, cleaner, more easily readable code.
function getStoreId() { // Removed async keyword
return prompt({ // Added return statement
title: 'Get StoreId',
label: 'Store ID:',
value: '',
inputAttrs: {type: 'guid'},
type: 'input'
})
.then((result) => {
if (result === null) {
console.log('user cancelled');
} else {
return result; // Return the result
}
})
// PS: Don't forget to handle any caught errors gracefully.
.catch(console.error);
}
// Called only when your getStoreId() function has resolved.
function useResult(result) {
// Do something useful with your result.
console.log(result);
}
// Calling "getStoreId()" without a ".then()" method will only
// return a "Promise { <pending> }" message at this point in the code.
// console.log(getStoreId());
// Let's show the prompt window.
getStoreId()
.then((result) => { useResult(result); })