简体   繁体   English

JS ES6 Promise Chaining

[英]JS ES6 Promise Chaining

I'm trying to learn how to use promises, but am having trouble comprehending the chaining. 我正在努力学习如何使用promises,但我很难理解链接。 I assume that with this code, both promises will run. 我假设使用此代码,两个承诺都将运行。 Then when I call test.then() it should know that test has resolved and pass the resolve data to then(). 然后,当我调用test.then()时,它应该知道测试已经解决并将解析数据传递给then()。

Once that function finishes, it goes onto the next then(), repeating the same process with the test2 promise. 一旦该函数完成,它将进入下一个then(),用test2 promise重复相同的过程。

However, I can only get it to print out the first promise results, not the second. 但是,我只能打印出第一个承诺结果,而不是第二个。 Any ideas what is missing here? 这里缺少什么想法?

var test = new Promise(function(resolve, reject){
    resolve('done1');
});

var test2 = new Promise(function(resolve, reject){
    resolve('done2');
});

test
.then(function(data) {
    console.log(data);
})
.then(test2)
.then(function(data) {
    console.log(data);
});

Your first .then call is returning undefined , whereas any subsequent .then is expecting a returned promise. 你的第一个.then调用返回undefined ,而任何后续.then都期望返回一个promise。 So you'd need to change your code to: 因此,您需要将代码更改为:

var test = new Promise(function(resolve, reject){
    resolve('done1');
});

var test2 = new Promise(function(resolve, reject){
    resolve('done2');
});

test
.then(function(data) {
    console.log(data);
    return test2;
})

.then(resultOfTest2 => doSomething)
.then(function(data) {
console.log(data);
});

You need to return next promise from the then callback: 您需要从then回调中返回下一个承诺:

test.then(function(data) {
    console.log(data);
    return test2;
}).then(function(data) {
    console.log(data);
});

you need to return the other promise(test2) in the first promise (test1) to allow for chaining: 你需要在第一个promise(test1)中返回另一个promise(test2)以允许链接:

  var test = new Promise(function(resolve, reject){
    resolve('done1');
});

var test2 = new Promise(function(resolve, reject){
    resolve('done2');
});

test
.then(function(data) {
  console.log(data);
  return test2;
});

Summary: 摘要:

The basic concept of promise chaining with promises is that every then / catch method on a fulfilled promise returns another promise. 承诺与承诺链接的基本概念是,履行承诺的每个then / catch方法都会返回另一个承诺。 It works in the following manner: 它的工作方式如下:

  • When a promise is resolved the callback passed in the then method is called. 解析promise时,将调用then方法中传递的回调。 The then method wraps the value which is returned in its callback in a resolved promise and returns this resolved promise . then方法将其回调中返回的值包装在已解析的promise中,并返回此已解析的promise
  • When a promise is rejected the callback passed in the catch method is called. 当promise被拒绝时,将调用catch方法中传递的回调。 The catch method wraps the value which is returned in its callback in a rejected promise and returns this rejected promise . catch方法将其回调中返回的值包装在被拒绝的promise中,并返回此被拒绝的promise

Example: 例:

Before fully understanding the concept of chaining multiple then methods it is important to know what exactly the return values of then and catch are. 之前充分了解链接多个概念then方法重要的是要知道究竟的返回值, thencatch的。 Take the following example: 请看以下示例:

 let prom1 = new Promise((res, rej) => { res('res'); }); const resolvedProm1 = prom1.then((val) => {return val}); // setTimeout needed for the promise to actually be resolved setTimeout(() => console.log(resolvedProm1)); let prom2 = new Promise((res, rej) => { rej('rej'); }); const resolvedProm2 = prom2.catch((err) => {throw err}); // setTimeout needed for the promise to actually be rejected setTimeout(() => console.log(resolvedProm2)); 

We can observe the status of the promises in the chrome devtools: 我们可以在chrome devtools中观察promises的状态:

承诺javascript

What basically happens is that in a then or catch callback is the following: 基本上发生的是在thencatch回调中如下:

  • Any value returned in a then or catch callback is wrapped in Promise.resolve() and a new resolved promise is returned. thencatch回调中返回的任何值都包含在Promise.resolve()并返回一个新的已解析的 promise。
  • Any error thrown in a then or catch callback is wrapped in Promise.reject() and a new rejected promise is returned. thencatch回调中抛出的任何错误都包含在Promise.reject()并返回一个新的被拒绝的 promise。

Because we are getting returned a rejected or resolved promise object we can repeat the cycle and call the then or catch method on it again. 因为我们正在返回一个被拒绝或已解决的promise对象,所以我们可以重复该循环并再次调用thencatch方法。 For example: 例如:

 const prom = new Promise((res, rej) => { if (Math.random() > 0.5) { res('success'); } else { rej('error'); } }); prom.then((val) => { return val; }).then((val) => { return val }).then((val) => { console.log(val) }).catch((err) => { console.log('err'); }) 

This calling of then and catch methods which are executed in their respective order is called promise chaining. 调用以各自顺序执行的thencatch方法称为promise chaining。 It is a very useful technique to make working with asynchronous code easier, especially if multiple asynchronous operations need to be performed which are dependend on each others data. 这是一种非常有用的技术,可以更轻松地处理异步代码,尤其是在需要执行多个异步操作时,这些操作依赖于彼此的数据。

You may also want to try - 您可能还想尝试 -

    let test = new Promise(function(resolve, reject){
        resolve('done1');
    });

    let test2 = new Promise(function(resolve, reject){
        resolve('done2');
    });

    try {
        let logOne = test();
        let logTwo = test2();
        console.log(logOne);
        console.log(logTwo);
    } catch(error) {
        console.error(error);
    }

In this way, you can also properly handle any promise dependencies. 通过这种方式,您还可以正确处理任何promise依赖项。 For example if test one relied on test two's data your could - 例如,如果测试一个依赖于测试二的数据你可以 -

try {
        let logOne = test();
        let logTwo = test2(logOne);
        console.log(logOne);
        console.log(logTwo);
    } catch(error) {
        console.error(error);
    }

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

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