0

How to get result value out of async await function? I am trying to get current chain ID in the MetaMask, I get object in return of the function. I am expecting 0x4, but it is not accessible outside of the function.

let account;
let currentChain;

const switchNetwork = async () => {
                currentChain = await ethereum.request({ method: 'eth_chainId' });
                console.log(currentChain + ' <- currentChain'); //for debug
                return currentChain; //tried
}

let fromCheck = switchNetwork();
console.log(fromCheck + ' <- fromCheck'); //for debug, expecting `0x4`

Result:

[object Promise] <- fromCheck
0x4 <- currentChain

Object looks like this:

Promise {<pending>}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: "0x4"
0x4 <- currentChain
Pang
  • 9,564
  • 146
  • 81
  • 122
Majoris
  • 2,963
  • 6
  • 47
  • 81

1 Answers1

1

In order to get a value out of a promise (the return type of an async function), you must use either .then(value => { ... }) or await.

In your specific case, this would look like:

let fromCheck = await switchNetwork();
console.log(fromCheck + ' <- fromCheck');

// or

switchNetwork()
    .then(val => {
        console.log(val + ' <- fromCheck');
    });
kalkronline
  • 459
  • 2
  • 12
  • `Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at ?chain=173:227:25)` I attempted that also earlier. Got it for `let fromCheck = await switchNetwork();` – Majoris Aug 01 '22 at 18:56
  • 2
    yes, you can only use await inside of async functions. since you're not using modules, you need to create a temp async function, something like main() to hold the await, or just use .then() – kalkronline Aug 01 '22 at 19:02