calling a async function inside then [duplicate] - javascript

This question already has answers here:
Removing nested promises
(2 answers)
Closed 7 years ago.
I have a piece of code that looks like this:
func().then(function (result){
var a = func1(result);
func2(a).then(function(result1){
////
}
}
As you can see func returns a promise, and in then part we call another func1 which also returns a promise. Is it possible to chain the promise returned from func2 with the promise of then, and somehow get ride of the nested functions in the second then.

The return value inside a then() function is used as a promise value itself. So you can easily return the new promise and keep on chaining here:
func()
.then(function (result){
var a = func1(result);
return func2(a);
})
.then(function(result1){
////
})
See 2.2.7 and 2.3.2 of the Promise A+ Spec.

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)

How can I return a value from .then method of 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 2 years ago.
In the following javascript code snippet (written for nodejs), the createDoc function returns a promise. Upon fulfillment of the promise, the handler passed to .then is invoked. The question is that how can I make .then return doc? According to the documentation, .then returns a promise but I'm really looking for it to return doc.
let p = createDoc(title).then(function (doc) {return doc;});
//p is a promise, and not doc
console.log(p);
What is the proper way to access the value passed to the fulfillment handler (doc in this case) outside the .then?
do something like this and when the promise resolves the value of doc will be inside p
let p;
createDoc(title).then(doc => p = doc);
You can use async-await, if you want to have the value instead of promise in p
async function someFunction() {
...
let p = await createDoc(title);
console.log(p);
...
}
What you are seeing is a behavior of promises calling chaining.

Calling Promise.resolve() on *potentially* non-promise values [duplicate]

This question already has answers here:
How to handle functions that do not always return a promise?
(2 answers)
Closed 4 years ago.
I have a situation where I need to check if a function returns a promise, the problem is, its a browser implemented function and some browsers DO return a promise and some don't. I was checking: How do I tell if an object is a Promise?, to see how to check if a function returns a promise and it recommends using Promise.resolve(). But what exactly happens when you call Promise.resolve() on a non-promisified function?
I tried reading this, but i wasn't able to find an answer to the question exactly: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
From the MDN documentation:
returns a Promise object that is resolved with the given value. If the value is a promise, that promise is returned; if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable.
So yeah wrapping that returned value with Promise.resolve would take care of promisifying that value.
You can assign what the function returns to a variable and then evaluate that variable like so:
var obj = whateverFunction();
if(typeof obj.then === "function"){
// This is a promise because it has a then function
}
Although I suspect the answer using Promise.resolve might be better.

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

Categories

Resources