#js array and promises different output in return an console.log()

9 messages · Page 1 of 1 (latest)

boreal mantle
#

hi i started to learn js and i tried to parse html i encountered a a problem can someone please explain to me why i get different outputs and what is the better solution to get the same result stored in the dataList and what is that " <1 empty item>"
https://paste.developerden.net/nonosytahy.js

eternal wadi
#

Await a

#

Well actually, await scrpData on the return line

#

I dunno if you can await on the top level...

#

Just a sec gonna check

boreal mantle
#

changed the link with package's added

#

i tried your way didn't work

eternal wadi
#

You can't await at the top level and since a is async the top level immediately goes to the log before ever running a. Two options.

  1. Use a second async function that does all the top level stuff so you can await.
async function a() {
    getHtml = await fetch("https://www.npmjs.com/");
    htmlText = await getHtml.text();

    return htmlText.substring(0, 20);
}


async function run() {
    dataList = await a();
    console.log(dataList);
}


run();
  1. Use then with a function (arrow function in this case)
async function a() {
    getHtml = await fetch("https://www.npmjs.com/");
    htmlText = await getHtml.text();

    return htmlText.substring(0, 20);
}

a().then(dataList => console.log(dataList));
#

I'd suggest the first option.