Did you know that in Nodejs https.get
does not return a promise ?
that means warping the request with async/await
won't work as you expect
I declared main() as an async function and chained the callback with then .. why does the console.log statement gets called first ???
and if I return the response instead of logging it, that's a
ReferenceError: Cannot access 'result' before initialization
Here's why :
In Node.js, the built-in http module provides methods for making HTTP/HTTPS requests, but it primarily uses a callback-style syntax, which is asynchronous and doesn't return promises.
So, while the regular function itself doesn't return a promise, when called using await, its return value behaves as if it were a resolved promise value.
To make HTTP requests using promises,
you can use the https.request
method in combination with the Promise constructor.
With this we make sure the promise has been resolved first.
Here's another example to make it clearer.
async function regularFunction() {
setTimeout(() => {
console.log("during await");
}, 1000);
}
const asyncFunction = async () => {
console.log("Before await");
await regularFunction().then(() => {
console.log("After await");
});
};
asyncFunction();
// before await
// after await
// during await
The regularFunction
is treated as if it were a resolved promise.
After the await
, the execution of asyncFunction
continues, "After await"
is logged to the console and then "during await"
after the callback execution is done.
I hope this was helpful.
this is my first post ❤️ . if you liked it give it a 👍
Top comments (2)
Excellent karem! Keep moving forward always.
❤️❤️❤️