0

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'

A. CLAUDE
  • 5
  • 3

1 Answers1

0

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?

Arye Eidelman
  • 1,579
  • 16
  • 22