Pergunta

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. 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). Here is my full code in jsfiddle.

Foi útil?

Solução

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.

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.

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top