异步函数不等待结束

时间:2021-07-31 01:16:12

标签: javascript reactjs async-await

我的目标是,如果第一个请求捕获错误,我不希望它发出另一个请求。基本上是有条件的请求。

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 得到一个错误(在通用类中),这就是我想要的。但是,在我发现错误之后;

if (!condition) {
            console.log("NOT valid.. closing..")

这部分不等待服务设置condition = false

Service.validation(payload).then(() => {
            condition = true;
        })**.catch(errorMessage => {
            condition = false;
        })**

它是一个异步函数,但代码不会等待它完成。

在控制台

“无效……关闭……”

“1”

我在这里遗漏了什么吗?

1 个答案:

答案 0 :(得分:1)

在行动。您需要致电 await

async function () => {
  let condition;
  await Service.validation(payload).....
  if (!condition) ...
}