Array push not working inside promise then [duplicate] - javascript

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

Related

Pause function until promise is resolved [duplicate]

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")
}

Object has contents, as long as I don't want to specifically adress them [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Console.log showing only the updated version of the object printed
(3 answers)
Closed 2 years ago.
I have this React project, in which I fetch data from a firebase database and construct a object called "statehelp" from the results. Now for some reason, if I console log the whole statehelp Object I get all its contents, however if I want to access statehelp.contents or statehelp.products they are undefined.
componentDidMount() {
var statehelp = {
content: {},
products: {}
}
getFarm(this.id).then(result => statehelp.content = result)
getProduct(this.id).then(result => statehelp.products = result)
console.log(statehelp)
console.log(statehelp.content)
}
That happens because console.log() is synchronous operation. It won't wait for your api call to happen. So don't use console.log() as a metric for identifying whether your object got populated or not.

How to show data outside of a subscribe scope/ how to use callback [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to show a list from an API call.
let url = 'api/list';
this.apiService.get<List[]>(url)
.subscribe((response) => {
this.list = response; // response has data
})
console.log(this.list); // no data shown
Because of async behavior the console always shows a blank list. How can I show the list with data outside of the subscribe scope. For clarification I need the list with data in the consoles position. I am familiar with the concept of callback. Do I need to use a callback function here? If yes, how can I achieve that?
The object the keyword this is pointing to is different in the places you are using it. So when you are setting this.list inside your callback function, you are setting the attribute list of your callback function.
One old skool way to fix this would be setting let that = this and then inside your callback function using that.list. By doing so you would be setting the attribute list of the keyword this that is one level above your callback function.
Hope it still makes some kind of sense.
Also look at Andrew Hills comment, it's full of logic :)

How to set the variable with chrome.storage.local.get in chrome [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
var curline;
chrome.storage.local.get("value",function(item)
{
window.curline=item["value"];
});
alert(curline);
I want to set the curline with item["value"],this code is in theinject.js,thanks.
chrome.storage API is asynchronous. The callback is executed later, after you alert.
Which means you must alert the result in the callback you pass :
var curline;
chrome.storage.local.get("value",function(item)
{
window.curline=item["value"];
alert(curline);
// here you may use curline, or pass it as argument to other functions
});

Trying to access a variable inside a jquery function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to access a variables inside a $.post jquery method. The code I have so far is below:
var fromDatabase;
$.post( "../read.php", function( data ) {
fromDatabase = JSON.parse(data);
console.log(fromDatabase); //this works fine
return fromDatabase;
});
console.log(fromDatabase); // but this gives me 0.
I am trying to get the from database variable so i tried to declare it outside the function to no avail.
Thank you.
You can't - you must continue program execution from within the callback, not immediately after the asynchronous $.post call.
You cannot return from an asynchronous function, that's the nature of asynchronicity. Instead, after your value is available (the callback function is called) you must work with the data within the scope of that function.
Perhaps a good starting point would be some Ajax tutorial. If you want more, simply google for JavaScript async.

Categories

Resources