Javascript promises. Continually repeat first promise until second promise resolves

So I’ve got a React App that creates a video, this is a very long api request taking between 1 and 10 minutes to resolve. I have a separate api call which I need to run continually every couple of seconds to check the status until the first promise is resolved (and the video is compiled).

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

Any idea how I can recursively call Promise2 until Promise1 Resolves?

26 thoughts on “Javascript promises. Continually repeat first promise until second promise resolves”

  1. Promises, by definition, are functions which return a value at most once, at a later point in time. You can’t re-run a promise, the best you can do is recreate one using some factory pattern.

    Alongside that, you need a mechanism to check if your create promise has been fulfilled.

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

Leave a Comment