2014-11-25 6 views
1

방금 ​​약속이 바뀌었고 잘못된 것이 있습니다. 그러나 무엇을 알 수는 없습니다. 다음 코드에서는 _getDevice()가 null을 반환하면 약속을 취소하고 싶습니다 (후드 아래 mongodb.findOneAsync()).'then'에서 약속을 취소하십시오.

_getDevice가 null을 반환하면 저의 관점에서 약속을 취소해야하며 'CANCEL REPLY'로그가 표시되어야합니다. 하지만 대신 'SAVE REPLY'로그가 나타납니다.

나는 블루 버드 라이브러리를 사용하고 있습니다. 그 콜백의 실행이 약속이 해결되었음을 의미로

var promise = Promise.props({ 
    device: _getDevice(event.deviceId), 
    events: _getEvents(event.deviceId, event.date) 
}).cancellable(); 

promise.then(function (result) { 
    if (! result.device) { 
     return promise.cancel() 
    } 

    var device = new Device(result.device); 
    var events = result.events; 

    // ... 

    return db.collection(collections.devices).saveAsync(device.toMongoDocument()); 
}).then(function() { 
    console.log('SAVE REPLY'); 
    return req.reply(null); 
}).catch(Promise.CancellationError, function (err) { 
    console.log('CANCEL REPLY') 
    return req.reply(null); 
}).catch(function (error) { 
    return req.reply(error); 
}); 

답변

4

당신은 then 콜백에서 약속을 취소 할 수 없습니다. 나중에 국가를 바꿀 수는 없습니다.

이 처리기에서 오류을 던져서 then()에서 반환 된 새로운 약속을 거부하게됩니다.

당신도이 약속이 합류하기 전에 getEvents 약속이 취소되도록 getDevice 약속이 실패 할 때 그렇게 할 수 있습니다

Promise.props({ 
    device: _getDevice(event.deviceId).then(function(device) { 
     if (!device) 
      throw new Promise.CancellationError(); // probably there's a better error type 
     else 
      return new Device(device); 
    }, 
    events: _getEvents(event.deviceId, event.date) // assuming it is cancellable 
}).then(function (result) { 
    var device = result.device; 
    var events = result.events; 

    // ... 

    return db.collection(collections.devices).saveAsync(device.toMongoDocument()); 
}).then(function() { 
    console.log('SAVE REPLY'); 
    return req.reply(null); 
}).catch(Promise.CancellationError, function (err) { 
    console.log('CANCEL REPLY') 
    return req.reply(null); 
}).catch(function (error) { 
    return req.reply(error); 
}); 
+0

대단한 답변입니다. 고맙습니다 ! – doobdargent

0

내가 허용 대답은 완전히 올바른 생각하지 않는다; Cancelling Long Promise Chains 참조 - 은 에서 약속을 취소 할 수 있으며입니다. 그러나 정확히 어떤 문제가 원래 질문과 관련이 있는지 확신 할 수 없습니다 (동작은 실제로 설명되지 않았습니다).

.cancellable()을 두 번째 약속의 끝에 넣으십시오.

+2

물론'then' 콜백에서 임의의 약속을 취소 할 수는 있지만 약속은 자체 콜백에서 취소 할 수 없습니다. 이것은 OP가 시도한 것입니다. – Bergi

+0

좋아, 나는 그 구별을 보지 못했다고 생각한다. 감사. – blah238

+0

언급 할 가치가있는 한 가지는 전체 취소 API가 다시 작성되는 것으로 간주된다는 것입니다. https://github.com/petkaantonov/bluebird/issues/415 – blah238