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