【发布时间】:2019-04-26 08:28:44
【问题描述】:
在设置完其他所有内容后调用订阅,但我想等到订阅完成。 T
尝试使用异步等待,但这对我不起作用。不知道是不是我做错了
public getGlobeConfig() {
this.sourceKey = 'test';query = 'query'
// wait till this call finishes than hit the
console.log('htting')
this.service
.searchQuery(query)
.subscribe(response => {
this.sources = response.hits.hits.map(hit =>
hit._source);
if (this.sources.length > 0) {
this.availableMetadata = Object.keys(
this.sources[0].metadata[this.sourceKey]
);
}
});
console.log('hitting')
return this.sources
}
This.sources 到达未定义,因为 this.sources 正在订阅中设置
【问题讨论】:
-
订阅是否返回回调或承诺,如果是,您可以尝试
.subscribe(...).then(console.log('hitting'); return this.sources) -
看起来你已经陷入了异步编程的经典错误之一:)。异步回调在函数返回后被调用,而不是同时调用。虽然 javascript 看起来执行顺序是
start search query->run callback->return a value,但实际上是start search query->return a value; (稍后:)run callback。不必立即调用 Clalbacks。他们甚至可以在几天后被调用。并且您的其余代码不会等待回调完成(因此是异步的)。 -
能否请您澄清您正在使用的库,并提供更多关于
searchQuery来自何处的背景信息?
标签: javascript angular async-await