作者:书友59082326 | 来源:互联网 | 2023-10-11 13:27
我想将JSON对象响应到路径(例如/ getabsencesWithNames)。我已经使用-webkit-appearance:none;
函数从JSON文件中读取数据,对其进行处理并将其保存在我尝试响应的全局JSON对象中。问题是以下命令includeNames()
异步执行,因为res.end(JSON.stringify(temp,null,"\t"));
函数中有I / O代码。如何使该命令等待功能完成,换句话说,使其同步运行?
includeNames()
控制台输出为:
function includeNames(){
members().then(membersPayload => {
// var counter = 1;
for (var i in respondJson){
var absencesID = respondJson[i].userId;
for (var j in membersPayload){
var membersID = membersPayload[j].userId;
if (absencesID == membersID){
var nameValue = membersPayload[j].name;
JSON.stringify(nameValue);
respondJson[i]["name"] = nameValue;
// console.log(counter + ": " + membersPayload[j].name);
// counter++;
break;
}
}
}
console.log("ITERATION COMPLETED");
}).catch((err) => console.error('error: ' + error.message));
return respondJson;
};
app.get('/getabsencesWithNames',async (req,res) => {
var temp = await includeNames();
res.end(JSON.stringify(temp,"\t"));
console.log("RESPOND SENT");
});
当我期待的时候:
RESPOND SENT
ITERATION COMPLETED
您必须重写函数以返回Promise。
function includeNames() {
return new Promise((resolve,reject) => {
members().then(membersPayload => {
// var counter = 1;
for (var i in respondJson){
var absencesID = respondJson[i].userId;
for (var j in membersPayload){
var membersID = membersPayload[j].userId;
if (absencesID == membersID){
var nameValue = membersPayload[j].name;
JSON.stringify(nameValue);
respondJson[i]["name"] = nameValue;
// console.log(counter + ": " + membersPayload[j].name);
// counter++;
break;
}
}
}
resolve(respondJson)
console.log("ITERATION COMPLETED");
})
});
};
// you cant use it as you're using
const result = await includeNames()
// or with Promise chain
includeNames().then(result => console.log(result))