【发布时间】:2019-03-27 04:56:20
【问题描述】:
我正在使用 Promises 更新我的 javascript 技能,已经有一个带有 XHR 和回调的库,可以一次加载和注入多个文件,并且只有在所有文件都成功时才继续。
我正在尝试使用 Promise.all() 和 Fetch API 来获得类似的功能,但无法使其工作:console.log('All the promises are resolved', values);无论某些 fetch 承诺是否失败,都会触发。
我希望能够执行下面的代码,并且只有在所有文件都能够被获取的情况下才继续使用 nowInitialize 函数,或者使用 catch() 抛出错误,原因是第一个文件失败
xRequire(['index.html', 'style.cds'])
.then(nowInitialize)
.catch(reason => 'One or more files failed to load' + reason)
style.cds 显然会失败
//TODO Handle file types appropriately
//TODO: Inject css, javascript files
function xRequire(files) {
let urls = [];
let promisesList = [];
let handleAllPromises;
//Populates urls with each file required
for(let i=0; i < files.length ; i++) {
urls.push(files[i]);
}
//Fetch each file in urls
urls.forEach( (url, i) => { // (1)
promisesList.push(
fetch(url)
.then(handleResponse)
.then(data => console.log(data))
.catch(error => console.log(error))
);
});
handleAllPromises = Promise.all(promisesList);
handleAllPromises.then(function(values) {
console.log('All the promises are resolved', values);
});
handleAllPromises.catch(function(reason) {
console.log('One of the promises failed with the following reason', reason);
});
}
function handleResponse(response) {
let contentType = response.headers.get('content-type');
console.log('Requested Info: ' + contentType);
if (contentType.includes('application/json')) {
return handleJSONResponse(response);
} else if (contentType.includes('text/html')) {
return handleTextResponse(response);
} else if (contentType.includes('text/css')) {
return handleTextResponse(response);
} else if (contentType.includes('application/javascript')) {
return handleTextResponse(response);
} else {
throw new Error(`Sorry, content-type ${contentType} not supported`);
}
}
function handleJSONResponse(response) {
return response.json()
.then(json => {
if (response.ok) {
return json;
} else {
return Promise.reject(Object.assign({}, json, {
status: response.status,
statusText: response.statusText
}));
}
});
}
function handleTextResponse(response) {
return response.text()
.then(text => {
if (response.ok) {
return text;
} else {
return Promise.reject({
status: response.status,
statusText: response.statusText,
err: text
});
}
});
}
【问题讨论】:
-
@CertainPerformance 你对这不是重复的事情并不认真吗?我的意思是一个简单的搜索显示 SO 上的多个配音......来吧。这是一个:stackoverflow.com/questions/31710768/…
-
@Akrion 我没有这么说,我只是说
async/await语法问题不是问题所要问的(问题中至少有几个问题)