简体   繁体   English

正确链接RSVP许诺的方法

[英]Proper way of chaining RSVP promises

So I have a function data.people() which sends and http request and receives data, therefore I am using promises and this function returns a promise. 所以我有一个函数data.people()发送和http请求并接收数据,因此我正在使用promises,并且此函数返回一个promise。 After that I use the folowing chaining 之后,我使用以下链接

data.people()
.then(function() {

    ....
}, function(err) {
    console.error(err);
}).then(function() {
        ...
}, function(err) {
    console.error(err);
}).then ...

So am I writing this correct, cause I can't find any documentary on this and when I attach an eventListener to one element with a given id in the third promise, it executes before the second promise is executed (where this element is changed with another with the same id) and doesn't work in the third promise (where I need it to). 所以我写的是正确的,是因为我找不到任何纪录片,并且当我在第三个承诺中将eventListener附加到具有给定id的一个元素上时,它会在第二个承诺执行之前执行(在此元素更改为另一个具有相同ID的文件),并且在第三个承诺(我需要的地方)中不起作用。 Here is my full code in jsfiddle. 是我在jsfiddle中的完整代码。

Yes, you are writing works but far from optimal. 是的,您正在撰写作品,但远非最佳。

There is no reason to chain .then calls unless you are returning a promise from one of them in which case it'll wait until the asynchronous operation will complete. 没有理由将.then链链接起来.then除非您从其中一个返回了诺言,在这种情况下,它将等待异步操作完成。

Your code can be simplified to: 您的代码可以简化为:

data.people().then(function(people){
    //rest of code here
});

Since none of your thens return promises. 既然您那时都没有回报承诺。

Promises that don't return a promise will continue to the next .then almost instantly. 不返回一个承诺承诺将继续到下一个.then几乎瞬间。

Also, if you do chain handlers and want to access the return value in later .then calls you have to return the data from that .then handler. 另外,如果您执行链处理程序,并且想在以后的.then调用中访问返回值,则必须从该.then处理程序中返回数据。

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

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