我很新的Node.js和异步编程。我试图使该混洗Spotify的播放列表中的程序。我把用户的播放列表到一个数组。
我想显示在网页上,为用户选择该阵列。一旦用户做出他们的选择,我想继续使用选定元素的程序。这是代码片段我迄今写的。
// Callback functions
function plCallback(selected_playlist) {
playlist_id =
console.log(playlist_id);
}
function getPlaylist(body, plCallback) {
// Pull user playlists
for (var i = 0; i < body.items.length; i++) {
playlistArray.push({'name': body.items[i].name, 'id': body.items[i].id});
}
// prompt user to select desired playlist to shuffle
var selPlaylist = document.getElementById('playlist-drop');
for (var i = 0; i < playlistArray.length; i++) {
var opt = playlistArray[i].name;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
// send selected playlist to Callback
var dropdown_return = document.getElementById('playlist-drop');
var selected_playlist = dropdown_return.options[dropdown_return.selectedIndex].value;
plCallback(selected_playlist);
}
我真的在为我甚至需要搜索,因为我很新的js和节点的损失。
总结:我填充Spotify的播放列表的JS数组。我想显示此列表给用户进行选择。一旦做出选择,我需要的程序继续使用上述选择。
我没有看到node.js的用武之地。但我认为你的“回调”的建设是不正确的..
这是函数调用getPlaylist()
功能plCallback()
并传递所获得的playlist
对象,
这并没有使getPlaylist()
asyncronous呢。
function plCallback(playlist) {
if (playlist) {
// Do something ..
}
}
function getPlaylist(body) {
var playlist = .. ;
plCallback(playlist);
}
// Your call ..
getPlaylist(body);
这是getPlaylist()
使用一个回调函数,回调getPlaylist()
的参数,并触发获取playlist
后,虽然,这仍然没有发生asyncronous。
“回调”建设的一大好处是,你可以为每个呼叫做不同的事情playlist
,因为没有定义固定plCallback()
功能。
function getPlaylist(body, plCallback) {
var playlist = .. ;
plCallback(playlist);
}
// Your call ..
getPlaylist(body, function(playlist) {
if (playlist) {
// Do something ..
}
});
现在,为了使功能异步,结账:qazxsw POI