0

I am facing a weired issue when creating a js promise chain.In promise,when I am using array function with (),I don'nt get the expected value.It give me the 'undefined' value in second then.

Here is the js code:

let x = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('[email protected]');
    }, 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);
    });

But when I didn't use the ()=>{} syntax inside the .then,I got the expected answer.

Here is the example of wright code:

let x = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('[email protected]');
    }, 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));

Can anyone please help me with this issue?

1
  • Your arrow function implementation is returning the promise y(res), but in your first example, you don't return the promise y(res), so it isn't being used in your promise chain: return y(res); Commented Feb 7, 2021 at 8:25

2 Answers 2

3

In order to chain promises you need to return Promise. This sample works correctly

x.then((res) => y(res))
    .then((res) => console.log(res))
    .catch((err) => console.log(err));

because (res) => y(res) means:

(res) => {
   return y(res)
}

and the result of y() promise is passed to the next .then So to solve your code you need to write it in this way:

x.then((res) => {
    // do some calculations
    return y(res);
})
    .then((res) => {
        // result of y promise
        console.log(res);
    })
    .catch((err) => {
        console.log(err);
    });
Sign up to request clarification or add additional context in comments.

Comments

2

Returning something from a function using curly braces {} means that you need to use keyword return to return something:

x.then((res) => {
  return y(res);
});

Using arrow functions, if no curly braces added, the immediately value after => is returned.

then((res) => console.log(res));

Comments

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.