I encountered a strange problem while working on a JS promise chain. When using an arrow function with parentheses in the promise, I am not getting the expected value. Instead, it gives me an 'undefined' value in the second 'then'.
Here is the JavaScript code:
let x = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f78498999283cec0c7b7909a969e9bd994989a">[email protected]</a>');
}, 2000);
});
function y(email) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(email);
}, 4000);
});
}
x.then((res) => {
y(res);
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
However, when I removed the ()=>{} syntax inside the .then, I received the correct output.
Here is the corrected code:
let x = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f2c30313a2b66686f1f38323e3633713c3032">[email protected]</a>');
}, 2000);
});
function y(email) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(email);
}, 4000);
});
}
x.then((res) => y(res))
.then((res) => console.log(res))
.catch((err) => console.log(err));
Could someone offer assistance with this issue?