2017-04-13 71 views
1

一個承諾我有醒目的錯誤時,不同的輸入遞歸調用自身的函數:解決從一個遞歸函數抓

function getSomething(inputs, index) { 

    var index = index || 0 
    , indexMax = inputs.length - 1 

    return new Promise((resolve, reject) => { 
    //inputs[index].staff is an array and getSomethingElse returns a Promise 
    Promise.all(inputs[index].staff.map(getSomethingElse)) 
    .then(output => { 
     resolve(output) 
    }) 
    .catch(reason => { 
     if(index<indexMax) 
     getSomething(inputs, index+1); 
     else 
     reject(reason); 
    }) 
    }) 
} 

getSomething(myInputs) 
.then(output => { 
    console.log('resolved with this:'+output); 
}) 
.catch(reason => { 
    console.log('rejected because of this:'+reason); 
}); 

我得到UnhandledPromiseRejectionWarning:未處理從getSomethingElse拒絕答應廢品。我認爲這種拒絕在第一次函數調用中並沒有像預期的那樣被捕獲。我怎樣才能調用第一個函數調用的拒絕?或者我應該在每次函數調用中將第一個承諾與我作爲參數?

+1

儘量'返回getSomething(輸入,指數+ 1)' – robertklep

+0

我只是去嘗試,得到了相同的結果.. – mouuu

回答

2

這是promise constructor anti-pattern。構造函數僅用於包裝傳統API

相反,鏈接承諾,因爲他們的意圖總是returning all of them

function getSomething(inputs, index = 0) { 
    return Promise.all(inputs[index].staff.map(getSomethingElse)) 
    .catch(reason => { 
     if (index >= inputs.length - 1) throw reason; 
     return getSomething(inputs, index+1); 
    }) 
    }) 
} 
+0

這是更好的,謝謝! – mouuu

0

我剛找到解決方案。其實,我應該爲了定義的決心和拒絕從返回承諾要傳輸到前一個:

if(index<indexMax) { 
    getSomething(inputs, index+1) 
    .then(output => { 
    resolve(output); 
    }) 
    .catch(reason => { 
     reject(reason); 
    }) 
} 
else 
    reject(reason);