简体   繁体   中英

How to create javascript promise chain with array function?

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('sonet970@gmail.com'); }, 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('sonet970@gmail.com'); }, 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 issu? Thanks for advanced.

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

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));

Thank you all for your answers.Now I understand,why my first code din't work.It all about array function,nothing w ith promises!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM