There are some more reasons besides the missing await statement before the call to fetch. The reason is because the fetch function does not in fact return a promise.
You set it as an arrow function. Arrow functions will do an implicit return if the function body only has a single expression. So the fetch function returns the result of the https.get() function call, which is just the function signature as it works with the callback concept.
Additionally you did not handle the event listener correctly, as the res.on('data', <function here>) line does not return a promise, so the await keyword did not do anything.
Let's see how I would rewrite your code to run as expected:
const https = require('https')
const substr = 'spider'
const pageNum = 1
let list = []
// Create an async function fetch that takes the url
const fetch = (url) => {
// Return a promise
return new Promise((resolve, reject) => {
// Call the https.get function
https.get(url, (res) => {
res.setEncoding('utf-8')
// Set the event listener
res.on('data', function (data) {
// Here the actual data event is _happening_. Now we have the return value
console.log(data) // 1st Log
resolve(data)
})
})
})
}
(async (substr) => {
totalPages = 1;
pageNum;
for (let i = 1; i <= totalPages; i++) {
// await the promise returned from fetch
const res = await fetch(
"https://jsonmock.hackerrank.com/api/movies/search/?Title=" +
substr +
"&page=" +
i
);
console.log(res);//2nd log
}
})("s");
I hope this attempt at an explanation helps!