-1

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

2 Answers2

2
    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();
Doo9104
  • 43
  • 1
  • 8
0

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:

  1. Use 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
     
    }
  1. Use .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
         }); 
    }
Arky Asmal
  • 1,162
  • 4
  • 10
  • but how do i assign the result to a variable outside of the async so that i can use it in another function? – Elusive_DODO May 19 '22 at 02:03
  • if you return the value inside the async function, you can call it in another function using await again. For example, const contract = await getContract() – Arky Asmal May 19 '22 at 02:16