我目前正在使用JavaScript中的fetch
API,并且我有一个几个月的数组,我想要从数据库中获取月份的值并且该值是正确的,但是随后在{{1 }}正在重新排列数组,如何防止重新排列数组?
console
然后结果: 有时
async function getMonthAccomplishment(m, s) {
this.m = m;
this.s = s;
const param_point = 'filecase/monthaccomplishment/' + this.m + '/' + this.s;
this.endpoint = url() + param_point;
return await fetch(this.endpoint, {credentials: 'include'})
.then((resolve) => {
if(resolve.ok) {
return resolve.text();
}
}, rejected => { console.error(rejected); })
.then((response) => {
return response;
}).catch((error) => {
console.error(error);
});
}
let PostMonthAccomplishment = function() {
this.m = '';
this.s = '';
this.t = '';
};
PostMonthAccomplishment.prototype.set = function(m, s, t) {
this.m = m;
this.s = s;
this.t = t;
if(typeof this.m === 'object' && typeof this.s === 'string') {
this.m.forEach((month) => {
getMonthAccomplishment(month, this.s)
.then((data) => {
console.log(month + ': ' + this.s + ' -> ' + data);
});
});
} else {
console.error('invalid typeof!');
}
};
const months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
const status = ['beginning+balance', 'case+receive', 'Decided/Report+&+Recom.+Submitted+from+Pending'];
let pma = new PostMonthAccomplishment();
pma.set(months, status[1], '');
有时
dar:27 january: case+receive -> 0
dar:27 april: case+receive -> 0
dar:27 may: case+receive -> 0
dar:27 march: case+receive -> 0
dar:27 june: case+receive -> 0
dar:27 february: case+receive -> 0
dar:27 july: case+receive -> 0
dar:27 august: case+receive -> 0
dar:27 september: case+receive -> 0
dar:27 october: case+receive -> 0
dar:27 november: case+receive -> 0
dar:27 december: case+receive -> 0
答案 0 :(得分:2)
如果您想按顺序执行操作,则很容易在await语句中简单地包含多行,并将输出从一个异步调用传递到另一个异步调用,就像通常用promises一样。您应该将数组数据放入异步函数中 像这样:并行请求的代码
async function processArr(arr) {
let pArray = []
for(const item of arr) {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/'+ item)
pArray.push(response.json())
}
const months = await Promise.all(pArray);
console.log(months)
return months
}
processArr([1, 2, 3])
依次p / s更新
async function processArr(arr) {
let pArray = []
for(const item of arr) {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/'+ item)
let data = await response.json();
}
}
processArr([1, 2, 3])