A variable inside async function derived from a promise has different value when returned to global scope [duplicate] - javascript

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I do not understand why the query variable has a value inside async function that changes when returned and declared in the global environment. I want to return the value from my database to a global variable outside of the async function.
What is the logically reason this happens. How do I extract the integer value from the Promise {1}.
async function glob(){
var result = await knex.raw('select max(glob) from or');
let query = await result.rows[0].max ;
console.log(query);
return query ;
}
let go = glob();
setTimeout(()=>{console.log(go)},1000);
setTimeout(()=>{console.log(go == 1)},1000);
The console returns.
1
Promise { 1 }
false

Related

Why does Chrome console return Promise object from .then() instead of the resolved value? [duplicate]

This question already has answers here:
Why does Promise.prototype.then always return promises?
(2 answers)
How can I access the value of a promise?
(14 answers)
Does then() really return a promise in all cases? [duplicate]
(2 answers)
promise.then() returns Promise { <pending> } [duplicate]
(3 answers)
Closed 7 months ago.
I'm trying to better understand promises and async code in Javascript.
In doing so, I wrote the following, simple async function in the Chrome console:
const myAsync = async() => 10;
As expected, myAsync returns a promise, but when I call .then() (i.e. myAsync().then(res => res)), then console displays Promise{<fulfilled>: 10}. The promise is clearly fulfilled, but I would expect it to display, simply, the value 10.
Interestingly, if I modify the body of my call to .then() to res => alert(res), the alert displays what I expect, just 10.

my object is modified inside a function that has a promise even if function returned [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)
console.log() async or sync?
(3 answers)
Closed 8 months ago.
i have the following function that should return a result object
function checkRegisteredStatus(addr)
{
let result ={status:"",registrationType:""};
instance.methods.isRegistered(session.id,addr).call().then((receipt)=>
{
let {status,registrationType}= receipt;
result["status"] = status;
result["registrationType"]= registrationType;
});
return result;
}
i want to use this function like this:
let result = checkRegisteredStatus(addr)
i have three problems :
1- when i used async/await pattern on isRegistered() method like this:
let result = await instance.methods.isRegistered(session.id,addr).call();
return result;
result object would be a promise with unfulfilled status, which is wired since the purpose of await is to return the result of the resolve callback, and this is the first time that happens to me, i did async/await before and it always returns the final result not a promise. why is this happening?
2- due to the first problem i had to re-write my function the old way which is using.then() method (as i pasted above) and it works, however i dont understand how come the checkRegisteredStatus function should finish execution and is popped off from the call stack then how is it being able to modify the result object?
Example:
let result = checkRegisteredStatus(addr)
console.log(result)
the output would be:
> {status:"",registration:""}
when i click the expand sign > it outputs the following:
> {status:"",registration:""}
registrationType: "NotRegistered"
status: false
as far as i understand the value was caught be console.log() when the result object still had empty properties that's why i could expand the object and see its props have different values,i think JS is adding elements from inside that promise that registered before, but the function result obj should be cleaned from the stack (since it returns immediately), how is it adding values to it even though the function is popped from the call-stack?
3- how should i rewrite my function such that it blocks execution until it returns the final result not a promise and not adding up values later.

How do I access data outside of the then scope when resolving a promise? [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.
Noob question here. Can someone elaborate on why seriesData variable outside the then scope is still an empty object. Additionally, what's the appropriate way of accessing data outside of said scope?
fetchData is a method that returns an array of three objects when successfully resolved.
Obviously, the console.log inside the then scope prints the expected seriesData object with the resulting data from the resolved promise.
Here's the code.
import fetchData from './data';
const seriesData = {};
fetchData()
.then(res => {
seriesData.characters = res[0];
seriesData.locations = res[1];
seriesData.episodes = res[2];
console.log(seriesData);
})
.catch(error => console.error(error.message));
console.log(seriesData);

returning a value from async/await promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to find a simple example of how to return a value from async/await where the value is easily accessed outside the async function.
Would the following two examples be considered the optimum way to return a value from an async/await function?
In other words, if the value returned from an async/await needs to be saved and used in other parts of the code, what would be the best way to save the value?
this is the easiest example i could find:
async function f() {
return 1;
}
var returnedValue = null; // variable to hold promise result
f().then( (result) => returnedValue = result );
console.log(returnedValue); // 1
or perhaps would it be better to use an object?
async function f(varInput) {
varInput.value = 1;
}
myObject = {} ; myObject.value=null;
f(myObject);
console.log(myObject.value); // 1
thank you.
My answer addresses two subjects here:
1) Async function returns a promise that resolves to a value. So, for instance your first function can be used as per your example. It can also be used like this:
async function() {
const x = await f();
}
2) Immutability - the second solution will work but it makes your funciton "impure". It is not bad in itself, but beware of side effects this might cause (for instance, if you change an app-wide singleton value without other components being notified about it, some part of your app might go out of sync with the data).
Hope this answers your question.

Undefined global variable when returning data generated in a nested function [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 5 years ago.
I have a function that I call which hits an API and returns a JSON, which I am calling getData. Inside that function is a nested function that processes the JSON and saves it to a new variable processedData when it's done making the request from the API.
I'd then like to return that processed JSON, but the console is telling me it's undefined. I didn't declare the variable so it should be treated as global. Why am I still having this issue?
The code won't work with the snippet because the API is only local, but processedData essentially looks like this: {'A': '123'}
function hitAPI() {
var getData = $.get('http://127.0.0.1:5000/myroute');
getData.done(function() {
processedData = (JSON.parse(getData['responseJSON']['data']));
});
return processedData;
};
var x = hitAPI()
console.log(x);

Categories