在调用另一个函数之前调用回调函数

时间:2021-03-01 10:23:17

标签: javascript reactjs

我有一个调用一个 API 的函数:

const response = fetch(APIfunctonName, {
    method: "POST",
    body: JSON.stringify(searchRequest),
    headers: {
        "Content-type": "application/json; charset=UTF-8",
    },
})
    .then((res) => res.json())
    .then(
        (result) => {
            let urlParams = this.getRequests();
            let reqid = urlParams["requested"];
            var newUrl = window.location.href
                .replace(`requestID=${reqid}`, "requestID=0")
                .replace("requestID=0", "requestID=" + result.RequestId); //result.RequestId always have proper one
            history.pushState({}, null, newUrl);
            this.getList(result.RequestId); //sometimes this goes as undefined
        },
        (error) => {
            console.log(error);
        }
    );

我总是在结果对象中得到正确的请求,但我不明白为什么有时我在 getList 函数中得到一个旧的 Id

2 个答案:

答案 0 :(得分:-1)

您可以按如下方式使用 Promise,以确保将正确的请求传递给下一条指令:

let p = new Promise((resolve , reject) => { 

 let urlParams = this.getRequests();
        let reqid = urlParams["requested"];
        var newUrl = window.location.href
            .replace(`requestID=${reqid}`, "requestID=0")
            .replace("requestID=0", "requestID=" + result.RequestId);
             history.pushState({}, null, newUrl);
        resolve(result);   
 }); 

 p.then((result)  => {
     this.getList(result.RequestId); 
 }); 

答案 1 :(得分:-1)

我认为原因是同步ajax和异步ajax之间的差异。

如果下面的 ajax this.getRequests()async。您的代码会出现一些意外错误。

let urlParams = this.getRequests();
  1. 第一个解决方案是将 async 更改为 sync

您可以将此 this.getRequests() 更改为 sync。您的代码可以正常工作。

  1. 第二种解决方案是使用 awaitasync
const response = fetch(APIfunctonName, {
    method: "POST",
    body: JSON.stringify(searchRequest),
    headers: {
        "Content-type": "application/json; charset=UTF-8",
    },
})
    .then((res) => res.json())
    .then(
        async (result) => {
            let urlParams = await this.getRequests();
            let reqid = urlParams["requested"];
            var newUrl = window.location.href
                .replace(`requestID=${reqid}`, "requestID=0")
                .replace("requestID=0", "requestID=" + result.RequestId); //result.RequestId always have proper one
            history.pushState({}, null, newUrl);
            this.getList(result.RequestId); //sometimes this goes as undefined
        },
        (error) => {
            console.log(error);
        }
    );