2015-12-03 43 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' 
    } 
} 
相关问题