[英]Async/Await on Callback not waiting
我正在使用 javascript API 查询 AMPS SOW。 我的功能如下所示:
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))
}
看起来我对 ampsClient.sow_query 的调用没有等待回调完成,因此返回一个空列表。 因此,我无法循环调用 function getAmpsData 中的数据。 我知道它与异步/等待有关,因为如果我只是在 getAmpsData 中执行 console.log(data),我可以在 promise 得到解决时看到数据(可能在 2 秒后)。 无论如何我可以得到这个工作吗?
如果我理解正确, getAmpsData
中的data
是预期的数组,但getData
中的data
是未定义的。 这不是 async/await 问题,您只是忘记添加return data;
获取getAmpsData
。
我不确定您使用的是什么 package。 但是,也许,它使用回调 function 来获得.sow
function - message.data
的结果。
根据您的逻辑, onMessage
function 将在data.forEach
完成后被调用,您可以尝试将console.log
行添加到onMessage
function。
也许,package 有一个重要的理由这样做。 但是,要解决此问题,您可以将.sow
function 包装到 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))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.