Home > OS >  Nodejs terminal returning promise instead of value
Nodejs terminal returning promise instead of value

Time:07-16

If i write my code in file and run using

node file.js

it waits for file to run and then returns.

but if I write my code in terminal using below flow

node

*paste code*

*press enter*

it returns immediately a promise

code:

(async ()=> {
    var solanaWeb3 = require('@solana/web3.js');
    let connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));
    let data = await connection.getBlockHeight();
    return data
})()

how can I wait terminal to complete above process then return with the value?

Thanks

CodePudding user response:

Await the async IIFE:

await (async ()=> {
    var solanaWeb3 = require('@solana/web3.js');
    let connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));
    let data = await connection.getBlockHeight();
    return data
})()

or type the function body as it is without return:

var solanaWeb3 = require('@solana/web3.js');
let connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));
let data = await connection.getBlockHeight();
data;
  • Related