基本上,我需要获取并使用Promise才能进行此练习。但是,我无法获得想要的结果。目的是从iTunes API中获取数据,并将响应编码为JSON,然后将其传递到我的辅助函数中。
//What I've tried
const URL_TEMPLATE = "https://itunes.apple.com/search?entity=song&limit=25&term={searchTerm}";
function fetchTrackList(param) {
let url = URL_TEMPLATE.replace('{searchTerm}', param);
let promise = fetch(url);
promise.then(function(res) {
return res.json();
})
.then(function(res) {
renderSearchResults(res);
});
}
//My render methods
function renderTrack(track) {
let newDiv = $('<img>');
newDiv.attr({src: track.artworkUrl100, alt: track.trackName, title: track.trackName});
$('#records').append(newDiv);
}
function renderSearchResults(obj) {
$('#records').empty();
obj.results.forEach(result => {
renderTrack(result);
})
}
//Now it's the time to practice using `fetch()`! First, modify the `index.html`
//file to load the polyfills for _BOTH_ the fetch() function and Promises, so
//that your example will work on Internet Explorer.
//Use version 2.0.4 of the `fetch` polyfill.
//Define a function `fetchTrackList()` that takes in a "search term" string as a
//parameter and uses the `fetch()` function to downloads a list of tracks from
//the iTunes Search API. You can use the below `URL_TEMPLATE` string for the URL,
//replacing `"{searchTerm}"` with the passed in search term (no {})
//Send the AJAX request, _then_ encode the response as JSON once it is received,
//and _then_ should call you `renderSearchResults() function and pass it the
//encoded data.
//
//IMPORTANT: Your `fetchTrackList()` method must also _return_ the Promise
//returned by the end of the `.then()` chain! This is so the method itself will
//be asynchronous, and can be further chained and utilized (e.g., by the tester).
//
//You can test this function by calling the method and passing it the name of
//your favorite band (you CANNOT test it with the search button yet!)
const URL_TEMPLATE = "https://itunes.apple.com/search?entity=song&limit=25&term={searchTerm}";
但是,我希望轨迹能够实际渲染。没有任何东西。我只能假设我做错了什么,但不知道该怎么做。