I'm currently teaching myself Javascript/Node.js, especially the concept of a Promise
and asynchronous operations. Recently while looking at some code on Github I've come across a peculiar piece of code that I'd love to have someone explain to me. Basically at the end of a function, there is this:
async myFunction() {
...
// Just wait forever, until signal
await new Promise(() => {});
}
What does the last line actually "do"? The comment above it just makes it even more confusing.
When I tried to execute the code, the function never returned. So I'm curious as to what that is supposed to do. Can someone explain that to me?
CodePudding user response:
This is because this promise is not resolving or rejecting and remains forever in pending state.
await new Promise((resolve) => { resolve()});
this above code will terminate your code because promise is resolved. see if this helps.
CodePudding user response:
When you run the code, the Promise will begin executing and awaiting a response from the inner method signature () => {}
. Until a response comes back, the Promise will then be taken into the status Pending. However, you can have a Promise that it'll never be resolved.
What () => {}
means is, give a set of empty parameters ()
, pass =>
them into the empty body {}
for use. But since there are no parameters and the body is empty, we are essentially stuck. The Promise will never fulfill the await
because nothing comes back - there is no return value.
Typically when you create a Promise, you'll want to bring in two parameters (resolve, reject), which would lead to two pathways, a pass or fail. Fulfilling either will get the Promise out of the pending state, completing the request.
Read up on this link here - Mozilla documentation on using promises
The key takeaway mentioned here on that site is that a value must always be returned. The code you are questioning, await new Promise(() => {});
will not return anything, but that will not stop other pieces of your code from executing during the await, so it's probably there to keep some process alive.
Another interesting note is when you add a then()
to that:
async myFunction() {
await new Promise(() => {}).then(() => {
console.log("I will never print to console log");
});
console.log("me neither, due to being scoped to await/async");
}
myFunction();
The then()
will never execute, nor anything after that. But if you take the async\await
out...
myFunction() {
new Promise(() => {}).then(() => {
console.log("I will never print to console log");
});
console.log("You'll see me in the console log");
}
myFunction();
console.log("You'll also see me in the console log too");
Anything after that promise will run.