【问题标题】:async function is not waiting for the end异步函数不等待结束
【发布时间】: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


【解决方案1】:

在行动。您需要致电await。

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

【讨论】:

  • 它解决了我的问题,但不再需要条件检查。我可以使用 try/catch 块来管理它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
  • 1970-01-01
相关资源
最近更新 更多