我如何不断重复第一个承诺直到第二个承诺解决?



我有一个React App创建一个视频,这是一个很长的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)});
};

任何想法我可以递归地调用允诺直到允诺解决?

promise,根据定义,是最多返回一次值的函数,在稍后的时间点。你不能重新运行一个承诺,你能做的最好的就是用一些工厂模式重新创建一个。

除此之外,你还需要一种机制来检查你的create promise是否已经完成。

// 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!");

我有另一种方法。如果不是挂在那里长达十分钟,发送任何需要的后端,一旦你得到它,发送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.的状态,你不需要在最后发送响应,你可以在任何时候这样做,你释放客户端,而服务器继续处理。

最新更新