Javascript 如何在node.js中强制后处理等待所有提取过程完成?
我使用fetch收集多个数据,然后在多个计算中使用它们Javascript 如何在node.js中强制后处理等待所有提取过程完成?,javascript,node.js,Javascript,Node.js,我使用fetch收集多个数据,然后在多个计算中使用它们 var data_dict = []; // objects with ids var fetch_data = function() { let data_history = []; data_dict.forEach(function (item, index) { let id = item.id; fetch(// with id) .then(res =
var data_dict = []; // objects with ids
var fetch_data = function() {
let data_history = [];
data_dict.forEach(function (item, index) {
let id = item.id;
fetch(// with id)
.then(res => res.json())
.then(data=>{// fix data})
.then(fixed_data=> data_history.push(fixed_data))
.catch(err => console.log(err))
});
return data_history;
}
var use_fetched_data = function () {
let results = [];
// use data_history in calculating results
return results;
}
var use_fetched_data2 = function () {
let results = [];
// use data_history and obtained results in calculating another results
return results;
}
// get data_history2
var data_history2 = fetch_data();
// use data_history2 to find results1
var results1 = use_fetched_data ();
// use data_history2 and results1 to find results2
var results2 = use_fetched_data2 ();
我尝试使用async&await强制等待,直到所有数据都被获取,但在获取完成之前仍然会计算结果
var force_wait = async function() {
// get data_history2
var data_history2 = await fetch_data();
// use data_history2 to find results1
var results1 = use_fetched_data ();
// use data_history2 and results1 to find results2
var results2 = use_fetched_data2 ();
}
force_wait();
如何正确地做到这一点
谢谢问题在于,fetch_data函数没有等待请求:
const fetch_data = async function () {
const data_history = [];
requests = data_dict.map(({ id }, index) => {
return fetch('https://randomuser.me/api/')
.then(res => res.json())
.then(data => data.results[0])
.then(fixed_data => data_history.push(fixed_data))
});
try {
await Promise.all(requests)
} catch (err) {
console.error(err)
}
return data_history
}
更改后,您的
force\u wait
应按预期工作。问题在于您的fetch\u data函数没有等待请求:
const fetch_data = async function () {
const data_history = [];
requests = data_dict.map(({ id }, index) => {
return fetch('https://randomuser.me/api/')
.then(res => res.json())
.then(data => data.results[0])
.then(fixed_data => data_history.push(fixed_data))
});
try {
await Promise.all(requests)
} catch (err) {
console.error(err)
}
return data_history
}
更改后,您的强制等待
应按预期工作