我已经在一个承诺中包装了jsonp请求,并且我正在进行一系列API调用,一旦它们全部解决后我想进一步处理。
var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "habathcx", "RobotCaleb", "noobs2ninjas", "twitchpresents"]
Promise.all(users.map(function(user){
var url = "https://wind-bow.gomix.me/twitch-api/users/" + user;
return jsonp(url);
})).then(function(arr){
console.log(arr);
})
它返回一个PromiseValue未定义的Promise数组,这不允许我进一步处理这些值。
我的JSONP承诺包装器在这里:
var count = 0;
var jsonp = function(url, options) {
options = options || {};
var prefix = options.prefix || '__jp';
var param = options.param || 'callback';
var timeout = options.timeout ? options.timeout : 15000;
var target = document.getElementsByTagName('script')[0] || document.head;
var script;
var timer;
var cleanup;
var cancel;
var promise;
var noop = function() {};
// Generate a unique id for the request.
var id = prefix + (count++);
cleanup = function() {
// Remove the script tag.
if (script && script.parentNode) {
script.parentNode.removeChild(script);
}
window[id] = noop;
if (timer) {
clearTimeout(timer);
}
};
promise = new Promise(function(resolve, reject) {
if (timeout) {
timer = setTimeout(function() {
cleanup();
reject(new Error('Timeout'));
}, timeout);
}
window[id] = function(data) {
cleanup();
resolve(data);
};
// Add querystring component
url += (~url.indexOf('?') ? '&' : '?') + param + '=' + encodeURIComponent(id);
url = url.replace('?&', '?');
// Create script.
script = document.createElement('script');
script.src = url;
target.parentNode.insertBefore(script, target);
cancel = function() {
if (window[id]) {
cleanup();
reject(new Error('Canceled'));
}
};
});
return {
promise: promise.then(function(data){
var user = {
name: data.name,
logo: data.logo,
};
userData.push(user);
}),
cancel: cancel
};
}
我可以在单个API调用中推送结果,但有没有办法从Promise.All访问值?
答案 0 :(得分:2)
你不会从承诺中归还任何东西。试试这个:
promise: promise.then(function(data){
var user = {
name: data.name,
logo: data.logo,
};
userData.push(user);
return user; // <-- pass data further
}),