Node.js 发出HTTP请求以等待响应中的特定属性
我向包裹递送公司的外部API发出了标准http.post请求。不幸的是,有时当我添加一个新包裹时,应该包含跟踪号的响应会将此属性返回为null。 我发现生成它需要一段时间,所以我添加了timeout并这样写:Node.js 发出HTTP请求以等待响应中的特定属性,node.js,angular,api,Node.js,Angular,Api,我向包裹递送公司的外部API发出了标准http.post请求。不幸的是,有时当我添加一个新包裹时,应该包含跟踪号的响应会将此属性返回为null。 我发现生成它需要一段时间,所以我添加了timeout并这样写: this.order.id = '11111111' const data:any = { //object of parcel } this.addParcel(data) //POST request .subscribe( response =&
this.order.id = '11111111'
const data:any = {
//object of parcel
}
this.addParcel(data) //POST request
.subscribe(
response => {
//this returns parcel object with id that is needed to get tracking_number
setTimeout( () =>
this.getTrackingNumber(response.id) //GET request
.subscribe(
response2 => {
const shipment = {
waybill: response2.tracking_number,
}
this.addTrackingNumber(this.order.id, shipment)
.subscribe(
response3 => {
console.log('success', response3);
},
error => console.log('oops', error)
);
},
error => console.log('oops', error)
),
1000);
},
error => console.log('oops', error)
);
在大多数情况下,它会按预期工作,但有时会返回getTrackingNumber()函数
追踪号码
属性,因为未指定生成该属性所需的时间
因此,我的问题是:
是否有任何可能的方法强制http请求等待tracking_number属性不为null
我也在考虑如果它返回的跟踪号码为空,就再次调用它,但我认为这不是一个好的做法。
不幸的是,setTimeout也不是理想的解决方案,因为生成跟踪_号所需的时间不同,有时几乎不需要时间,有时甚至超过给定的1000毫秒
在这个项目中,我使用Angular和Nest.js,所以我可以选择在前端或后端编写它
谢谢你的建议
你好