2016-07-30 3 views
2

저에게 잘 맞는 체인 연결을 얻으려고합니다. 이 상황을 내가 모두 foobar하고 서명을 제대로하려고 쓰고에서체인 연결 기능이 올바르게 생성됩니다.

promise.then(foo.then(bar)); 

:

promise.then(foo).then(bar); 

과 :

나는 문제가 사이의 차이를 이해 귀결 생각 . barfoo에 의해 생성 된 반환 값을 사용합니다.

나는 후자가 있지만, 내 질문은 이전 작업을하기 위해 무엇을해야합니까?

위와 관련된 내용은 전체 코드 (아래)입니다. 나는 (기대 log1, log2, log3, log4, log5하지만 log3, log4, log5, log1, log2을 받고) 내가 기대하고있는 순서대로 인쇄 다른 로그가 없습니다. 위의 내용을 잘 이해하고 있기를 기대하고 있습니다.

var Promise = require('bluebird'); 

function listPages(queryUrl) { 
    var promise = Promise.resolve(); 

    promise = promise 
    .then(parseFeed(queryUrl) 
     .then(function (items) { 

     items.forEach(function (item) { 
     promise = promise.then(processItem(transform(item))) 
        .then(function() { console.log('log1');}) 
        .then(function() { console.log('log2');}); 
     }); 

    }).then(function() {console.log('log3')}) 
).then(function() {console.log('log4')}) 
    .catch(function (error) { 
    console.log('error: ', error, error.stack); 
    }); 
    return promise.then(function() {console.log('log5');}); 
}; 
+2

두 번째 것은 잘못되었습니다. 'then'은 약속이 아니라 콜백을 인수로 사용합니다. – Bergi

+0

@Bergi - 'then'에 또 다른 약속을하고 싶다면 콜백이 약속을 반환하는지 확인해야합니까? – Vineet

+1

@Vineet 예, Promise를 반환하는 함수를 전달해야합니다. Promise는 반환하지 않습니다. – nem035

답변

2

promise.then(foo).then(bar);promise.then(foo.then(bar));의 차이점은 무엇입니까?

두 번째 것은 잘못되었습니다. then 메서드는 약속이 아니라 콜백을 인수로 사용합니다. 첫 번째는 (foo는 약속도를 반환한다고 가정)

promise.then(function(x) { return foo(x).then(bar) }) 

에 해당하므로 그 콜백은, 약속을 반환 할 수 있습니다.


전체 코드가 조금 엉망인 것 같습니다. 아마 읽어야합니다

function listPages(queryUrl) { 
    return parseFeed(queryUrl) 
    .then(function (items) { 
     var promise = Promise.resolve(); 
     items.forEach(function (item) { 
      promise = promise.then(function() { 
       console.log('log1'); 
       return processItem(transform(item)); 
      }).then(function() { 
       console.log('log2'); 
      }); 
     }); 
     return promise; 
    }).then(function() { 
     console.log('log3') 
    }, function (error) { 
     console.log('error: ', error, error.stack); 
    }); 
} 
+0

콜백 내부에서'var promise = Promise.resolve();'를 옮긴 이유가 있습니까? 밖에있을 때 작동하지 않을까요? (나는 당신의 코드가 더 깨끗하다는 것에 동의하지만, 나는 단지 이해의 틈을 이해하려고 노력하고있다). – Vineet

+1

@Vineet : 가능합니다. 가능한 한 변수를 지역 변수로 유지해야합니다. 그것은 바깥 쪽 범위에서도 초기화 할 수 있었지만 원래 코드에서는'listPages' 함수에서'return promise'를했지만,'promise'가 비동기 콜백에서만 할당 될 때는 작동하지 않습니다. 변수와 할당을 완전히 피할 수 있었고 (for?), forEach 대신에'reduce'를 사용할 수도있었습니다. 중요한 부분은 '약속'이'then' 콜백에서 반환된다는 것입니다. – Bergi