2015-12-03 44 views
1

我打電話給分機knex,然後使用該結果撥打電話RESTaxios。我使用的Observable來管理整個事情。這裏是我的代碼不工作像我想:爲什麼我必須在我的Rx流中指出索引?

return Observable 
     .fromPromise(knex('users').where({id: userId}).select('user_name')) 
     .map(res => getCreatePlaylistConfig(res[0].user_name)) 
     .concatMap(axios) 
     .toPromise(); 

function getCreatePlaylistConfig(userName) { 
    return { 
     url: 'https://api.spotify.com/v1/users/' + userName + '/playlists', 
     method: 'POST' 
    } 
} 
我有使用在 mapindex,我叫 getCreatePlaylistConfig使代碼工作

。我記錄的是來自與knex回調對象:

do(res => console.log(res)

,它看起來像這樣:

[ { user_name: 'joe'} ] 

它是一個數組像我所期望的,但我認爲map將遍歷數組。爲什麼它需要index?我如何使這段代碼正常工作?

回答

2

問題是您的代碼沒有展示Promise的結果。當你使用fromPromise時,你確實說你想創建一個Observable,它發出一個單一的值,然後完成(如果你看看fromPromise的來源,這正是它的作用)。在你的情況下,單個值是一個數組。

map運算符將對從源Observable發出的每個值和發出的值作用到另一個值。但是,它不會嘗試弄平那樣的數據,因爲那樣會比較放肆。

如果你想避免顯式使用索引操作符,你需要使用一個操作符來代替它。

return Observable 
     .fromPromise(knex('users').where({id: userId}).select('user_name')) 
     //flatMap implicitly converts an array into an Observable 
     //so you need to use the identity function here 
     .flatMap(res => res, 
        //This will be called for each item in the array 
       (res, item) => getCreatePlaylistConfig(item.userName)) 
     .concatMap(axios) 
     .toPromise(); 

function getCreatePlaylistConfig(userName) { 
    return { 
     url: 'https://api.spotify.com/v1/users/' + userName + '/playlists', 
     method: 'POST' 
    } 
} 
相關問題