2017-07-06 29 views
7

Spodziewam się, że poniższy kod wydrukuje jeden numer na konsoli, następnie odczekaj chwilę, a następnie wydrukuj kolejny numer. Zamiast tego natychmiast drukuje wszystkie 10 cyfr, a następnie czeka dziesięć sekund. Jaki jest właściwy sposób tworzenia łańcucha obietnic, który zachowuje się jak opisano?Tworzenie łańcucha obietnic w pętli for

function getProm(v) { 
    return new Promise(resolve => { 
     console.log(v); 
     resolve(); 
    }) 
} 

function Wait() { 
    return new Promise(r => setTimeout(r, 1000)) 
} 

function createChain() { 
    let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; 
    let chain = Promise.resolve(); 
    for (let i of a) { 
     chain.then(()=>getProm(i)) 
      .then(Wait) 

    } 
    return chain; 
} 


createChain(); 

Odpowiedz

13

Musisz przypisać wartość zwracaną .then powrotem do chain:

chain = chain.then(()=>getProm(i)) 
     .then(Wait) 

Teraz będzie można w zasadzie robić

chain 
    .then(()=>getProm(1)) 
    .then(Wait) 
    .then(()=>getProm(2)) 
    .then(Wait) 
    .then(()=>getProm(3)) 
    .then(Wait) 
    // ... 

zamiast

chain 
    .then(()=>getProm(1)) 
    .then(Wait) 

chain 
    .then(()=>getProm(2)) 
    .then(Wait) 

chain 
    .then(()=>getProm(3)) 
    .then(Wait) 
// ... 

Możesz zobaczyć, że pierwszy jest łańcuchem, a drugi jest równoległy.