Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass outer variable into promise .then without calling it

I have a series of promise functions that I'm chaining together. I don't need the specific result from the previous function so I'm not adding anything into resolve(); I just need them to run sequentially.

However, there is a variable in the containing scope that I want to pass into the first and fourth(last) promise. When I add it as a parameter to the third promise, the function runs immediately.

How can I pass a parameter into a chained promise and not call the function/promise at that time?

Here is the basics of what I'm trying to do:

const containingFunction = function() {
        const varToPass = document.querySelector("#ID").value.trim();
        firstPromise(varToPass)
            .then(secondPromise)
            .then(thirdPromise)
            .then(fourthPromise(varToPass))
            .catch(e =>{
               console.error(e)); 
            } );
    };

FourthPromise:

    const fourthPromise = function(varPassed) {
            return new Promise(function(resolve, reject) {
                do some stuff but only after the thirdPromise has been resolved
                console.log(varPassed)
                resolve();
            });
        };

2 Answers

You have two possibilities depending on how you want to resolve varToPass.

Lambda

Using a lambda function (anonymous function without own scope) as described by @Jaromanda X:

() => return fourthPromise(varToPass)

which will cause the function to keep a reference to the variable and not its value. The value of varToPass will be evaluated as soon as the fourthPromise is fired, not when this code is run.

Wrapper

The second option is using a wrapper, i.e. a function that returns a function:

function fourthPromise(varToPass) {
    return function() {
        return new Promise(function(resolve, reject) {
            do some stuff but only after the thirdPromise has been resolved
            console.log(varToPass)
            resolve();
        });
    };
}

In this case the value of the passed variable is evaluated at the time this code runs and not when the callback is called.

Which option is better applicable to your case we can't tell without more context though.

like image 75
Hubert Grzeskowiak Avatar answered Jan 03 '26 17:01

Hubert Grzeskowiak


Very simple change

const containingFunction = function() {
    const varToPass = document.querySelector("#ID").value.trim();
    firstPromise(varToPass)
        .then(secondPromise)
        .then(thirdPromise)
        .then(() => fourthPromise(varToPass))
        .catch(e =>{
           console.error(e)); 
        } );
};
like image 21
Jaromanda X Avatar answered Jan 03 '26 17:01

Jaromanda X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!