im new to javascript and struggling with the concepts, how do i access the return value of the async function outside of it, i have tried a .then method but it only returns undefined... this is my code, i want to assign the result to the contractNumber variable outside of the async function so i can pass it to another function and also console.log the result externally... im coming over from learning python so im super confused
const inquirer = require('inquirer')
async function getContract() {
await inquirer.prompt({
type: 'input',
name: 'retrieveContract',
message: "Enter contract adress: ",
})
.then(answer => {
console.log(`Targetting: ${answer.retrieveContract}`);
results = answer.retrieveContract
return results
});
}
getContract()
contractNumber = results
const inquirer = require('inquirer')
async function getContract() {
const result = await inquirer.prompt({
type: 'input',
name: 'retrieveContract',
message: "Enter contract adress: "
})
console.log(`Targetting: ${result.retrieveContract}`);
return result.retrieveContract;
}
contractNumber = await getContract();
To understand what's happening, await waits for the promise of inquirer.prompt to resolve into a return value, that you can then work with. There is no need for a .then clause, to work with the returned value.
There are two solutions:
await, and simply continue writing your logic. (My preferred solution since its cleaner and more intuitive) async function getContract() {
const answer = await inquirer.prompt({
type: 'input',
name: 'retrieveContract',
message: "Enter contract adress: ",
})
console.log(`Targetting: ${answer.retrieveContract}`);
results = answer.retrieveContract
return results
}
.then, and pass in the callback function on .then async function getContract() {
inquirer.prompt({
type: 'input',
name: 'retrieveContract',
message: "Enter contract adress: ",
}).then(answer => {
console.log(`Targetting: ${answer.retrieveContract}`);
results = answer.retrieveContract
return results
});
}