简体   繁体   中英

Async/Await on Callback not waiting

I am querying AMPS SOW using javascript API. My functions look like this:

sow_query = async(topic, filter, options) => {
await this.connection
await this.client.sow(this.onMessage, topic, filter, options)
return this.message
}

onMessage = (message)=>{
this.message.push(message.data)
}

//Calling functions
const getData = async(date) =>{
let data = await getAmpsData(date)
}

async getAmpsData(date){
const filter = "some filter"
const data = await ampsClient.sow_query(topic, filter)
data.forEach((element) => console.log(element))
}

It looks like my call to ampsClient.sow_query doesnt wait for the callback to finish so returns an empty list. Therefore, I cannot loop through the data in my calling function getAmpsData. I know it has to do with async/await because if I simply do console.log(data) in getAmpsData i can see the data (perhaps after 2 seconds) when the promise is resolved. Is there anyway i can get this working?

If I understand you correctly, data in getAmpsData is an array as expected, but data in getData is undefined. It's not an async/await problem, you just forgot to add return data; to getAmpsData .

I not sure about what package you are using. But, maybe, it using a callback function to get the result of .sow function - message.data .

With your logic, onMessage function will be called after data.forEach done, you can try adding a console.log line to onMessage function.

Maybe, the package has an important reason to do that. But, to fix this issue, you can wrap .sow function into a promise.

sow_query = async (topic, filter, options) => {
  await this.connection // ???
  return new Promise((resolve) => { // wrap in a promise
    this.client.sow( // no need to wait .sow
      (message) => {
        resolve(message.data); // just resolve when we get the message's data
      },
      topic, filter, options)
  });
}

//Calling functions
const getData = async (date) => {
  let data = await getAmpsData(date)
}

async getAmpsData(date) {
  const filter = "some filter"
  const data = await ampsClient.sow_query(topic, filter)
  data.forEach((element) => console.log(element))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM