Reputation: 414
Is there a way to hang/pause the function in the middle of its execution and then continue after few things are handled(input from the user received through socket.io) in node js? I know this is bad practice and need to use promises, async/await etc. However, according to the functionality of my program, I need to handle it this way.
My original question where I shared my code is here: Node application interactively get user input from react front end by pausing the current execution
Upvotes: 0
Views: 948
Reputation: 36574
You can do that with async
,await
and Promise
.
function func1(){
console.log("function 1 is finished")
}
function func2(){
console.log("function 2 is finished")
}
const thingsHandled = new Promise((res,rej) => {
func1();
func2();
console.log("Every function is done")
res();
})
async function main(){
await thingsHandled;
console.log("function is continued");
}
main();
Upvotes: 0
Reputation: 5837
... "pause the function in the middle of its execution" is unlikely to really be describing what you want to have happen. I assume you have some asynchronous code running that is responsible for getting your program to a point where "a few things are handled" ... so you code looks something like
var a_few_things_have_been_handled = false;
handle_a_few_things();
// which returns immediately but has a side effect of
// effectively setting a_few_things_have_been_handled to true
while(!a_few_things_have_been_handled) {
// do nothing just wait...
// actually you want to yield to asynchronous threads
// but you can't do it like this
}
the_rest_of_your_program();
Unfortunately that's not how the language works... you have to restructure your program flow to be explicit about sequential program flow using Promises or similar asynchronous flow control constructs.
Upvotes: 1
Reputation: 390
you can do it using async/await feature in javascript. rewrite any callback-based function to use Promises, then await their resolution.
Upvotes: 0
Reputation: 432
You can wrap "second block" of your function in setTimeout()
call, like this:
function f()
{
statement1;
setTimeout(() => {
statement2;
}, 1000);
}
Upvotes: 0