returning a value from async/await promise [duplicate] - javascript

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.

Related

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 to block execution of a function (i.e., force synchronous behaviour)? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
What is the JavaScript version of sleep()?
(91 answers)
Closed 3 years ago.
Requirement:
I need to write a function that takes an array of objects. Each item in the array has a state; if state === 'processing', a delay of 2 seconds is implemented before moving on to the next item. In other words, I actually need to block execution of the function for 2 seconds before looking at the next element in the array. When an element's state is not 'processing', the function returns an object and no further array elements are looked at.
The problem:
I can't think of any way to create a delay without using asynchronous approaches. I've written code (see below) which relies on Promise, but this does not satisfy the requirements, as with any asynchronous approach the Promise will return immediately; the delay only delays promise resolution not function execution. Thus, I wonder if there isn't a way of doing this synchronously, of blocking return of the function until after any delays are implemented.
My question:
Is there a way to accomplish this synchronously, to block execution of the code for a specified period of time before returning an object?
My code, which uses an asynchronous approach:
function wait(delay, callback, arg) {
return new Promise(resolve => {
setTimeout(() => {
resolve(callback(arg));
}, delay);
});
}
function getProcessingPage(data) {
const currentObj = data[0];
const state = currentObj.state;
if (state === 'processing') {
return wait(2000, getProcessingPage, data.slice(1));
}
return Promise.resolve({});
}
The solution:
Since this question has been closed (wrongly, in my opinion), it can not be answered, but I now have an answer. The answer is not performant in the least bit — it is not considered good practice and should never find its way into production code — but it does exactly what I needed to do for this exercise. The solution is to use while to prevent any code execution during the desired delay. See below:
function wait(delay) {
const delayUntil = performance.now() + delay;
while (performance.now() < delayUntil) {
// do nothing, as the while statement blocks execution
}
}
function getProcessingPage(data) {
const currentObj = data[0];
const state = currentObj.state;
if (state === 'processing') {
wait(2000);
return getProcessingPage(data.slice(1));
}
return {};
}

Variable scope issue when accessing Firebase from Node.js [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
My current code for accessing my Firebase databse from Node.js looks roughly like this.:
var DesiredValue = "#";
ref.child("Example").once("value", function(snapshot) {
DesiredValue = snapshot.val();
console.log(DesiredValue)
});
console.log(DesiredValue)
It returns
>42
>#
where 42 is the value I want to grab, but I can't figure out how to retrieve it outside the scope of ref.child.(). I have tried the following which doesn't work.
var DesiredValue = ref.child("Example").once("value", function(snapshot) {
var DesiredValue = snapshot.val();
console.log(DesiredValue)
return DesiredValue
});
console.log(DesiredValue)
All I want to do is use 42 in the remainder of the code. Based on what I have read there might be some way of using JavaScript's 'this' to achieve my goal, but I am worried of messing with global variables and think there must be an easier way?
It's a callback you may use a promise, when it is resolved then you can use the value out of function or handle the value inside the callback, otherwise the code it's executed without waiting

In Node.js Does all the function with a callback as a input parameter is non-block? [duplicate]

This question already has answers here:
Are all javascript callbacks asynchronous? If not, how do I know which are?
(5 answers)
Closed 7 years ago.
I am a little confusing about the async function and sync function, how can I determine if it is an async function?
My assumption is all the function which accept a callback is non-block and async, but here is a exception I found:
I found the Array.prototype.forEach is a block function even if it accept a callback as a parameter.
function test(){
[1,2,3,4,5].forEach(function(item){
for(var i =0; i<100000; i++){
console.log('test');
}
});
console.log('end');
}
test();
this function will continue to print test until all the callback finish, it won't return at once to run console.log('end')
really confusing, how can I determine if a function will return at once?
You can use the common sense rule here, is there any need for async in your code? Why do we need to delay the function? All of the array items are available for you, even if they were not, there should be another reader for example which is async then populate the array with avaialble items and then iterate over them. If you need async you will notice this for sure.

return value after a promise [duplicate]

This question already has answers here:
setting a variable to get return from call back function using promise
(2 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 8 years ago.
I have a javascript function where I want to return the value that I get after the return method.
Easier to see than explain
function getValue(file){
var val;
lookupValue(file).then(function(res){
val = res.val;
}
return val;
}
What is the best way to do this with a promise. As I understand it, the return val will return before the lookupValue has done it's then, but the I can't return res.val as that is only returning from the inner function.
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

Categories