简体   繁体   English

.then 方法中链接承诺与值之间的区别?

[英]Difference between chaining promises vs values in .then methods?

for a while, I thought the only way to chain .then() statements was to return a promise from the .then method.有一段时间,我认为链接.then()语句的唯一方法是从 .then 方法返回一个 promise。 eg:例如:

    asyncFunc()
       .then(res => asyncFunc2()) // returns a promise
       .then(res => doSmth())

But now I figured out that you can actually also return a plain old value from the .then function and it also works:但现在我发现你实际上也可以从 .then 函数返回一个普通的旧值,它也可以工作:

    const build = () => new Promise((resolve, reject) => {
        setTimeout(() => {
        resolve("Hallo")
      }, 100)
    })
    
    build()
        .then(res => {
        console.log(res);
        return res + " I'm";
      })
      .then(res => {
        console.log(res + " Peter");
      })

Is there a difference between the two in terms of how and when they are executed?两者在执行方式和时间方面是否有区别?

Each .then() method call returns a promise, if the return value of the callback function is also a promise, then the promise returned by the .then() method call gets resolved to that promise, meaning its fate will now depend on what happens to the promise returned by the callback function.每个.then()方法调用都会返回一个 Promise,如果回调函数的返回值也是一个 Promise,那么.then()方法调用返回的.then()会解析为该 Promise,这意味着它的命运现在将取决于什么发生在回调函数返回的承诺上。 It will settle when the promise returned by the callback function settles.当回调函数返回的承诺稳定时,它就会稳定。

On the other hand, if you return a non-promise value, then that value is implicitly wrapped in a promise and passed to the next .then() method call, if there's any.另一方面,如果您返回一个非承诺值,那么该值将被隐式包装在一个承诺中并传递给下一个.then()方法调用(如果有的话)。 If you don't return anything from the callback function, the promise returned by the .then() method will resolve with the value of undefined .如果您不从回调函数返回任何内容,则.then()方法返回的承诺将使用undefined的值解析。

In first code example, as you are returning asyncFunc2() from the callback function of first .then() method, the promise returned by it will get resolved to the promise returned by asyncFunc2() .在第一个代码示例中,当您从第一个.then()方法的回调函数返回asyncFunc2() ,它返回的承诺将被解析为asyncFunc2()返回的承诺。

In the second code example, res + " I'm" will be implicitly wrapped in a promise and then passed to second then() method.在第二个代码示例中, res + " I'm"将被隐式包装在一个 promise 中,然后传递给第二个then()方法。

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

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