我呼叫knex
的数据库,然后使用该结果与REST
进行axios
通话。我正在使用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'
}
}
我必须使用index
中的map
来调用getCreatePlaylistConfig
来使代码正常工作。我使用:
knex
调用回来的对象
do(res => console.log(res)
它看起来像这样:
[ { user_name: 'joe'} ]
这是一个像我期望的数组,但我认为map
将遍历数组。为什么需要index
?如何使此代码正常工作?
答案 0 :(得分:2)
问题是您的代码没有展平Promise
的结果。当您使用fromPromise
时,您实际上是说要创建一个Observable
来发出单个值,然后完成(如果您查看fromPromise
的来源,这正是它的作用)。在您的情况下,单个值是一个数组。
map
运算符将对从源Observable发出的每个值以及 map 它对另一个值起作用。但是,它不会尝试压平这些数据,因为这样做会相当冒昧。
如果你想避免明确使用索引操作符,你需要使用一个操作符来代替它。
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'
}
}