Promises Help - Returning Values [duplicate] - javascript

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.

Related

How to use promise on callback from proprietary software [duplicate]

This question already has answers here:
How to "await" for a callback to return?
(5 answers)
How do I convert an existing callback API to promises?
(24 answers)
Closed last year.
I'm using a software that lets me read a data on it's server using this function :
webMI.data.read(nodeID, function(e){...})
Passes a current property object for every data variable specified by its nodeID to the callback function. You can pass a single nodeID or an array of nodeIDs.
In the callback i get the value i want, but i couldn't get it out and didn't want to make a callback hell
After some reading/testing on asyncronous function, i tried using promise but i keep getting the same error and i don't understand why
webMI.data.read("AGENT.OBJECTS.motor.isActive",e => e.value)
.then(result => {
console.log(result)
})
Uncaught TypeError: webMI.data.read(...) is undefined
I also tried to put it in an async function and using await
async function GetValue(){
var temp = await webMI.data.read("AGENT.OBJECTS.motor.isActive",function(e){return e.value})
return temp
}
But temp always return a Promise with state = fullfilled and value = undefined
My goal is to get 1 to X values this way to make a formula
Note that i have no way to modify 'webMI.data.read'
Use the promise constructor and resolve from within the callback
function GetValue(){
return new Promise(resolve => {
webMI.data.read("AGENT.OBJECTS.motor.isActive",function(e){resolve(e.value)})
})
}
Now the GetValue function is async, as it returns a promise and can be awaited.
How to "await" for a callback to return?

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)

Bind a Promise return inside a get function [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 5 years ago.
Hello im new in typeScript and Angular.
I need to get a value in storage, the storage.get return a promise, so i try:
getNomeUsuario():string{
var that = this;
this.storage.get('nomeUsuario').then(function(nome){
that.nomeUsuario = nome;
}.bind(this));
return this.nomeUsuario;
}
The problem is that always return a undefined.
I also get the same with an arrow function.
getNomeUsuario():string{
this.storage.get('nomeUsuario').then((nome)=>{
this.nomeUsuario = nome;
});
return this.nomeUsuario;
}
How can I return the nome value ?
Sorry about my English hehe
Since this.storage.get("nomeUsuario") is asynchronous, there's no way the getNomeUsuario() method can return it's value without returning a Promise, so you'll need to do it like this:
getNomeUsuario(): Promise<string> {
return this.storage.get("nomeUsuario");
}
And handle the Promise where you call getNomeUsuario().
ps: you could also use an Observable, but it would add complexity without any benefits.
this.storage.get('nomeUsuario') executes asynchronously, and when you returns that.nomeUsuario, the promise wasn't executed yet and that.nomeUsuario still undefined. Try to insert this return into .then section like this:
getNomeUsuario():string{
var that = this;
this.storage.get('nomeUsuario').then((nome)=>{
that.nomeUsuario = nome;
return that.nomeUsuario;
});
}

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.

JavaScript function returns empty string when a value is expected [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
There's probably an obvious mistake somewhere, but I just can't out find what's wrong.
I'm trying to retrieve data from an api, and use the js-function below to get it. If I do an alert(key) on the data inside the $.get-function, it alerts the correct data.
function getApiKey(company, password) {
var url = "http://myapi.com/" +company+ "?password=" +password;
var key = "";
$.get(url).done(function(data) {
key = data;
//alert(key) returns the correct data
});
return key;
}
However, I need to use the function in a different file, and that's where it doesn't work. When I do
var key = getApiKey("company", "password");
alert(key);
key is empty.
The $.get command is asynchronous, meaning that your function returns key with its initial value of "", then later when the async callback fires, it runs key=data.
You should read up on asynchronous behaviour in javascript - for a solution, you'll need some way to get the data back to the place of the call asynchronously. One such option is a promise.

Categories

Resources