1

I am trying to develop a global function to use it more easily from another file.

At one point in my job I have this:

            .then(function(response) {
                if(response.data.code == 200)
                {
                    Swal.fire({
                        title: 'Modifications enregistrées !',
                        icon: 'success',

                        }).then(function() {
                            console.log(response);

                            // a parameter function which will used here
                            afterFinish();

                        });
                }

So in the second then (), I can access the response in console.log.

Now, I call a function that I had passed as a parameter. This function must also use the "response" attribute. Except it doesn't work.

Example :

My afterFinish function parameter :

afterFinish: function(response){
  console.log(response);
}

So in my main function it should give something like:

then(function() {
     console.log(response);

     // a parameter function which will used here
     //afterFinish function;
     console.log(response);

});

The 1st console.log () will send me the correct Response object. The second will return an empty Response object to me.

On the other hand, if I put the content of my afterFinish () function directly in the code instead of calling it, then necessarily I can access it.

Anyone know what to do?

1
  • You code is expecting you to pass it and you are doing afterFinish(); so um afterFinish(response); ??? Commented Feb 21, 2020 at 16:24

1 Answer 1

1

Pass response into afterFinish:

afterFinish(response)

Accept it as a parameter in afterFinish (I think you're already this part):

afterFinish: function(response) {
    // ...
}

Live Example using setTimeout for asynchronousness:

function fakeAjax() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(Math.random());
        }, 800);
    });
}

function myFunction(options) {
    const {afterFinish} = options;
    fakeAjax()
    .then(response => {
        afterFinish(response);
    })
    .catch(error => {
        // ...handle/report eror...
    });
}

console.log("Running...");
myFunction({
    afterFinish: function(response) {
        console.log(`Response is ${response}`);
    }
});

Sign up to request clarification or add additional context in comments.

1 Comment

Yes it works, thank you very much ! I had tried this solution which seemed logical to me, except that I also added the response property in the then, hence the fact that it did not work. Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.