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

callback function call before calling another function

提问人:Sanman Chavan 提问时间:3/1/2021 最后编辑:Blundering PhilosopherSanman Chavan 更新时间:3/1/2021 访问量:204

问:

我有一个调用一个 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

JavaScript 反应 JS

评论

0赞 Blundering Philosopher 3/1/2021
我相信这取决于您的 api 端点()。当我们不知道该端点如何工作时,我们如何提供帮助?APIfunctionName

答:

-1赞 Amine Dakhli 3/1/2021 #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赞 morgan-wu 3/1/2021 #2

我认为原因是同步 Ajax 和异步 Ajax 之间的分歧。

如果下面的 ajax 是异步的。您的代码将出现一些意外错误。this.getRequests()

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

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

  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);
        }
    );

评论

0赞 Rumesh 3/1/2021
由于问题似乎与对象有关,而不是 getRequests 返回,我认为这不是根本问题。即使是异步的,它也不会对对象中包含的内容产生任何影响resulturlParamsthis.getRequests();result