【发布时间】:2021-12-22 12:44:02
【问题描述】:
我知道有很多基于 Promise 的问题和答案,但我想做的是用 axios 检索一些数据(到微服务),然后使用这些数据发送另一个请求(到不同的微服务)。
不知何故,我想出了如何设置我的请求:
screenshot from console with the request right before axios call
问题是在后端我只有前两个子句。我认为这是因为我使用了 async/await 来成功避免 Promise 并获得实际的结果/类。我的意思是,也许请求是在承诺完成之前发送的,但是我如何在控制台中正确获取请求?
我是 Javascript 的新手,所以欢迎任何帮助。
编辑:
这是我的代码:
getServicesList = async (instanceIds) => {
return await FlowsInventoryAPI.searchServices(instanceIds, this.props.salesline, this.props.environment, this.props.sources, this.props.targets)
.then((response) => {
return response;
})
.catch((error) => {
Toastr.error(ResponseErrorProvider.getError(error));
if (ResponseErrorProvider.isUnauthorized(error)) {
Toastr.error(error.response.data.message);
this.props.onLogout();
}
});
}
以上是我谈到的第一个电话。
buildSearchObject = (size, page, status) => {
let interval = TimestampUtils.getInterval(this.props.logsTimeInterval);
let from = interval.from * 1000;
let to = interval.to * 1000;
return {
fromMillis: from,
toMillis: to,
size: size,
page: page,
salesline: this.props.salesline,
environment: this.props.environment,
routes: this.props.routes,
sources: this.props.sources,
targets: this.props.targets,
customFilters: [...this.props.filters.values(), ...this.getEnabledAdvancedFilters().values()],
status: status === LogStatus.ALL ? "" : status,
sortFieldName: this.props.sortColumn,
order: this.props.sortOrder,
searchFilter: this.props.searchFilter,
searchFilterOperator: this.props.searchFilterOperator,
applications: this.props.applications,
openedStores: this.props.openedStores,
servicesPromise: this.state.servicesList // here is the promise
}
};
searchLogs = (size, page, status, callback) => {
loadingService.showLoadingModal("loadingLogsPage", this.props.location.pathname);
let searchObject = this.buildSearchObject(size, page, status);
ElasticSearchApi.search(searchObject, this.props.token)
.then(response => {
callback(response);
})
.catch((error) => {
loadingService.hideLoadingModal("loadingLogsPage", this.props.location.pathname);
Toastr.error(ResponseErrorProvider.getError(error));
if (ResponseErrorProvider.isUnauthorized(error)) {
Toastr.error(error.response.data.message);
this.props.onLogout();
}
});
};
我在最后一段中有第二个调用,它调用了包含我们承诺的 buildSearchObject 方法。正如我告诉你的那样,我想出了如何将它作为值发送,但我认为由于“异步性”,我的诺言可能在第二次调用时还没有准备好,这就是为什么我的代码有状态的诺言。
编辑 2:
constructor(props) {
super(props);
this.ongoingRequestId = undefined;
this.ongoingRequests = new Map();
this.state = {
servicesList: this.getServicesList(this.getInstanceIds())
}
}
这是我的构造函数,我在其中创建我的 this.state.servicesList。
【问题讨论】:
-
你没有向我们展示你的代码,所以我们不可能告诉你你做错了什么......但是你想打第一个电话,返回一个承诺,然后在该承诺的解决方案内(在第一次通话完成时触发),您进行第二次通话。如果您向我们展示您的实际操作(请以文字形式,而不是屏幕截图),您将获得更直接的答案。
-
您写了
this.state.servicesList // here is the promise,但不清楚您在哪里初始化该状态属性或在哪里调用getServicesList(…)
标签: javascript asynchronous async-await promise axios