简体   繁体   English

如何使用数组 function 创建 javascript promise 链?

[英]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.在创建 js promise 链时,我遇到了一个奇怪的问题。在 promise 中,当我使用数组 function 和 () 时,我没有得到预期的值。

Here is the js code:这是js代码:

 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.但是当我没有在.then 中使用 ()=>{} 语法时,我得到了预期的答案。

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.为了链接承诺,您需要返回 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) => y(res)意味着:

(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:并且 y() promise 的结果被传递给下一个.then所以要解决你的代码,你需要这样写:

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:使用花括号{}function返回一些东西意味着您需要使用关键字return来返回一些东西:

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!谢谢大家的回答。现在我明白了,为什么我的第一个代码不起作用。这都是关于数组 function,没有任何承诺!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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