【发布时间】:2021-07-31 01:16:12
【问题描述】:
我的目标是,如果第一个请求捕获错误,我不希望它发出另一个请求。基本上是有条件的请求。
Action.js
let condition;
Service.validation(payload).then(() => {
condition = true;
}).catch(errorMessage => {
console.log("1")
condition = false;
})
if (!condition) {
console.log("NOT valid.. closing..")
return;
} else {
console.log("VALID.. Calling another service")
const promise = AnotherService.anotherRequest(url, payload);
return promise.then().catch();
}
Service.js
async validation(payload) {
return this.createOrUpdate(payload, "check");
}
crud 的泛型类
async createOrUpdate(data, subPath = "") {
try {
if (data.id) {
const response = await this.rc().put(this.PATH + subPath, data);
return response.data;
}
const response = await this.rc().post(this.PATH + subPath, data);
return response.data;
} catch (error) {
throw this.handleError(error);
}
}
rc = (responseType = "json") => {
return axios.create({
baseURL: this.RS_REST_URL,
validateStatus: (status) => (status === 200 || status === 201),
headers: {
"Content-Type": CONTENT_TYPE_JSON,
"Authorization": "Bearer " + localStorage.getItem(STORAGE_KEY_AT)
},
responseType: responseType,
paramsSerializer: (params) => qs.stringify(params, {arrayFormat: "repeat"})
});
}
我提出一个请求 const response = await this.rc().post 得到一个错误(在 Generic 类中),这就是我想要的。但是,在我发现错误之后;
if (!condition) {
console.log("NOT valid.. closing..")
这部分不等待服务设置condition = false
Service.validation(payload).then(() => {
condition = true;
})**.catch(errorMessage => {
condition = false;
})**
它是一个异步函数,但代码不会等待它完成。
在控制台中
“无效..关闭..”
“1”
我错过了什么吗?
【问题讨论】:
-
您的
Service.validation缺少await -
return await this.createOrUpdate(payload, "check");不能解决我的问题。内部类有等待。
-
jeah,但你使用的是
async,所以承诺将被解析为承诺
标签: javascript reactjs async-await