Node.JS async await issue

I have a bit of code that’s not executing. Can’t seem to find out why.
Help please.

    if(err) {
        console.log(err);
    }
    
    //Why is this code not getting executed?
    oldIP = data.trim();
    await console.log("Old IP is :"+oldIP);
});
let oldIP = "";
await console.log("Public(NEW) IP Address is: "+ ip);    

await fs.readFile('Currentaddress.txt', 'utf8',async (err,data)=>{
    if(err) {
        console.log(err);
    }
    
    //Why is this code not getting executed?
    oldIP = data.trim();
    await console.log("Old IP is :"+oldIP);
});

Are you getting any error messages?

Hi randell. No actually. The console.log(below the comment) doesn’t fire. Neither does the one that logs the error.

Take out the async and await keywords entirely. They don’t apply to any of the code you’ve written. If you want to learn how to use them, check out a tutorial like this.

1 Like

Hey @PortableStick. I’ve looked at the tutorial. Pretty sure I have it right. From what they’re showing.

The code is wrapped in an aynsc function like this:

(async =>{
ip = "192.168.100.12";

let oldIP = "";
await console.log("Public(NEW) IP Address is: "+ ip);    

await fs.readFile('Currentaddress.txt', 'utf8',async (err,data)=>{
    if(err) {
        console.log(err);
    }
    
    //Why is this code not getting executed?
    oldIP = data.trim();
    await console.log("Old IP is :"+oldIP);
});

})();

The purpose of async/await functions is to simplify the behavior of using promises synchronously and to perform some behavior on a group of Promises. Just as Promises are similar to structured callbacks, async/await is similar to combining generators and promises.

Like I said, async/await don’t apply to anything you’ve written. They don’t work with synchronous functions like console.log, and fs.readFile would need to be wrapped in a promise, which is doable.

function getFile(path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, 'utf-8', (err, data) => {
            if(err) reject(err);
            else resolve(data);
        });
     });


async function getCurrentAddress() {
    let oldIP = await getFile('Currentaddress.txt');
    console.log("Old IP is: " + oldIP);
}

getCurrentAddress();

Oooh. I now understand what you mean. Thanks very much. It worked

I’ll read up more on this.