2015-10-09 80 views
1

我有一個承諾鏈,我執行一些操作。當我達到某個then聲明時,我想創建一個可以繼續鏈的分支,但否則將解決整個即將到來的承諾鏈。有條件地完成承諾鏈

readFile('example.json').then(function (file) { 
    const entries = EJSON.parse(file); 
    return Promise.each(entries, function (entry) { 
     return Entries.insertSync(entry); 
    }); 
    }).then(function() { 
    if (process.env.NODE_ENV === 'development') { 
     return readFile('fakeUsers.json'); 
    } else { 
     // I am done now. Finish this chain. 
    } 
    }) 
    // conditionally skip these. 
    .then(() => /** ... */) 
    .then(() => /** ... */) 
    // finally and catch should still be able to fire 
    .finally(console.log.bind('Done!')) 
    .catch(console.log.bind('Error.')); 

這可能與承諾有關嗎?

+0

你的代碼說'insertSync',應該是'insertAsync'? –

回答

4

您可以如果您正在使用Node.js的V4.0.0 +,那麼你可以使用箭頭功能這樣

附加條件 then處理程序,在條件本身返回的承諾,這樣

readFile('example.json').then(function (file) { 
    return Promise.each(EJSON.parse(file), function (entry) { 
     return Entries.insertSync(entry); 
    }); 
    }).then(function() { 
    if (process.env.NODE_ENV === 'development') { 
     return readFile('fakeUsers.json') 
     .then(() => /** ... */) 
     .then(() => /** ... */); 
    } 
    }) 
    .finally(console.log.bind('Done!')) 
    .catch(console.log.bind('Error.')); 

.finally(() => console.log('Done!')) 
    .catch(() => console.log('Error.'));