2016-03-22 32 views
0

拒絕我想從func()reject持有錯誤,而不是直接向onError()通過的choise,漁獲物的承諾

之前,我總是讓func()resolve,並確定yield func()後,
如果我想直接到返回結果onError()使用throw ..;

想知道任何更好的主意,我就可以讓func()reject但detemire yield func()後,直接到onError()或不

co(function*() { 
    yield func(); 
    // if reject catch here, not direct to onError 


    yield func(); 
    // if reject don't catch here just direct to onError 

}).then(function (response) { 
    response = JSON.stringify(response); 
    res.send(response); 
}, function (err) { 
    onError(err); 
}); 


// ... 
func: function() { 
    return new Promise(function (resolve, reject){ 
    ... 
    reject(); 
    }); 
}, 

回答

1

co支持try/catch

co(function*() { 
    try{ 
     yield func(); 
    } 
    catch { 
    // if reject catch here, not direct to onError 
    } 




    yield func(); 
    // if reject don't catch here just direct to onError 

}).then(function (response) { 
    response = JSON.stringify(response); 
    res.send(response); 
}, function (err) { 
    onError(err); 
}); 

見文檔:https://www.npmjs.com/package/co#examples

+0

非常感謝! – user1575921