我怎样才能不断重复第一个承诺直到第二个承诺解决?

时间:2021-02-16 21:36:05

标签: javascript promise axios es6-promise

所以我有一个创建视频的 React 应用程序,这是一个很长的 api 请求,需要 1 到 10 分钟来解决。我有一个单独的 api 调用,我需要每隔几秒钟连续运行一次以检查状态,直到第一个承诺得到解决(并编译视频)。

        const promise1 = axios.post("/api/create", data);
        //promise1 takes between 1 and 10 minutes to resolve (video creation).

        const promise2 = axios.get(`/progress-${uniqueId}.txt`);
        // I need promise2 (which checks status of promise1) to continually run
        //at an interval (every 5 seconds?) until promise 1 resolves


        Promise.race([promise1, promise2]).then(res=>{
            //this obviously returns promise2 first, as expected, but 
            //once it comes back I need it to refire after 5 seconds
            //continually until promise 1 resolves
            console.log(res)});
    };

知道如何递归调用 Promise2 直到 Promise1 解决吗?

2 个答案:

答案 0 :(得分:0)

承诺,顾名思义,是在以后的某个时间点至多一次返回一个值的函数。你不能重新运行承诺,你能做的最好的事情就是使用某种工厂模式重新创建一个。

除此之外,您还需要一种机制来检查您的创建承诺是否已实现。

// Send create request
const creationPromise = axios.post("/api/create", data);

// Track creationPromise state
let isCreated = false;
creationPromise.then(() => isCreated = true);

// factory for creating a new progress request on-demand
const progressFactory = () => axios.get(`/progress-${uniqueId}.txt`);

// While the created request hasn't completed, loop
while (!isCreated) {
   // Send new progress request
   const progress = await progressFactory();
   console.log("progress", progress);
}
// Done, create returned
console.log("Finished!");

答案 1 :(得分:0)

好吧,我有另一种方法。如果不是挂在那里长达十分钟,而是在收到后立即将所需的任何内容发送到后端,然后发回 202 = The HyperText Transfer Protocol (HTTP) 202 Accepted response status code indicates that the request has been accepted for processing, but the processing has not been completed; in fact, processing may not have started yet. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. 的状态,您不必在最后发送响应您可以随时执行此操作,这样做是在服务器继续处理时释放客户端。