Pause function until promise is resolved [duplicate] - javascript

This question already has answers here:
How to wrap async function calls into a sync function in Node.js or Javascript?
(9 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
What is the JavaScript version of sleep()?
(91 answers)
Closed 1 year ago.
My function keeps executing indefinitely, although I would have expected it to resume after 10ms. Is there any way I can flush timeouts while I am waiting for the result? Or at least tell JS to execute / resolve other promises before I return my result?
The simple matter is, I NEED the response before I can continue execution. And I can not put my code in an async block whatsoever. I also can not use 'then' since I need to return the raw result. I thought this hack would work, but nope.
As far as my understanding of JS goes, this simply is not possible, but I would love to know.
let test = function () {
let wait = true;
setTimeout(() => {
wait = false
}, 10);
while (wait);
return wait;
}

you can use async/await , to block the flow of the function
example
const mine = async() => {
console.log("start")
await anotherAsyncFunction()
console.log("done")
}

Related

How to make event-triggered Cloud Function to "pause" while running? [duplicate]

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Javascript sleep/delay/wait function
(6 answers)
Closed 11 months ago.
I have my Nodejs Cloud Function executing some quick tasks upon invocation. I need to delay its termination by 20 seconds. What is the way to do this in the code?
Assuming you absolutely need this and you will not use this in production, this should be pretty straightforward if this is an asynchronous function.
Just define an async function that will return after an arbitrary amount of time:
async function sleepMS(timeMS) {
await new Promise(res => setTimeout(res, timeMS))
}
then after all your code runs and before your function returns, call it with the amount of time you wish
await sleepMS(20 * 1000)

Why is 'await' necessary for javascript? [duplicate]

This question already has answers here:
Understanding the Event Loop
(4 answers)
Closed 1 year ago.
My understanding is that javascript is single-threaded, meaning it will only execute one line at a time.
For the following code, why is 'await' necessary? I think it will still execute fetch before it moves to the next line:
const res = await fetch('http://testurl.com');
Can someone explain the importance of await in single-thread languages?
Thank you
Two types of functions can be 'paused' mid-function,
Async functions
Generator functions
So while you are correct, only 1 line will be executed at a time, await basically tells Javascript:
This function is now paused, and resume this function once this promise resolves.
While the function is paused, other code can run. But the 'only 1 line of code will run'-rule still holds.

Array push not working inside promise then [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I can't see what I'm doing wrong...push not working and returns nothing
import {nearbyUsers, getLatitude, getLongitude} from './helper'
const users = []
nearbyUsers(session, getLatitude(), getLongitude()).then(res => {
users.push(res)
console.log(users.lenght) //this works fine
})
console.log(users.lenght) //this prints 0
The problem is that the then callback happens asynchronously, meaning that there may (and probably will) be a delay between when the code inside the then callback is executed and the rest of the code outside of it.
If you want to depend on an async function, be sure to read about async/await. The await keyword, when put before an async function, will halt the program until the promise is resolved.
For more see here and here

Await fetch not working as expected in Javascript [duplicate]

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
Async function returning promise, instead of value
(3 answers)
Closed 1 year ago.
Why output from code below is PromiseĀ {<pending>} instead of Response.
What I doing wrong? Also await fetch("https://...") not working.
function asynchronousFunction() {
return fetch("https://thatcopy.pw/catapi/rest/")
}
const mainFunction = async () => {
const result = await asynchronousFunction()
return result;
}
console.log(mainFunction())
You shouldn't think of Promises and async functions (which return Promises) as something you can use to return a value at top-level. It's usually a bad idea that comes from the imperative and synchronous programming mindset.
Use chaining instead, either move the console.log inside mainFunction, or write this:
asynchronousFunction()
.then(console.log)

How to get a value from a callback? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have this line of codes:
let message = channel.consume(queue, msg => {
console.log('Return this in the "message" variable', msg.content);
});
When I tried to log the value of message, it does not equate to msg.content but it gets the value from the return of consume method. What's the workaround in order for me to get the right value from the callback.
Thanks
var message;
channel.consume(queue, msg => { message = msg.content; });
Not really sure what you're asking, but are you trying to set message within the callback? If so, see above.
You cannot "return" the value of the callback. Also, there's little point in doing so since the line after that code will execute before the callback has even executed.
While it's not "returning" the value, you can use a Promise.
If you can transpile from ES7, you can use async-await which allows you to call asynchronous functions using synchronous-looking code within an async function using await.

Categories

Resources