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

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?

Related

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)

Calling asynchronous functions from an array [duplicate]

This question already has answers here:
Resolve promises one after another (i.e. in sequence)?
(36 answers)
How to execute promises sequentially, passing the parameters from an array?
(9 answers)
How to chain execution of array of functions when every function returns deferred.promise?
(7 answers)
Closed 2 years ago.
PromisesInSeries function that takes an array of asynchronous functions and sequentially (the next one starts when the previous one has finished) calls them, passing the result of calling the previous function as arguments
function promisesInSeries(asyncFns) {
let result;
return new Promise((resolve, reject) => {
for(const fn of asyncFns){
resolve(fn)
.then(data => fn(data))
}
})
}
I only get the results of the first function. How to call all functions from an array and, as a result, return the last value?
Without async/await you could reduce the fns array:
function promisesInSeries(fns) {
return fns.reduce((promise, fn) => promise.then(fn), Promise.resolve());
}
The first fn will receive the value undefined, after that each return value is passed to the next function.
If you want to have some initial value, you can provide it by changing Promise.resolve() to Promise.resolve(initialData). Where initialData could be a static value or a value passed through function parameters.
If you can use async-await, this is way easier:
async function promisesInSeries(asyncFns) {
let result;
for (const fn of asyncFns) {
result = await fn(result);
}
}

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 a async function inside then [duplicate]

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.

Promises Help - Returning Values [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

Resources