如何在JavaScript中对GET方法做出同步响应

时间:2019-11-05 21:05:56

标签: javascript node.js

我想将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, null, "\t"));
    console.log("RESPOND SENT");
});

当我期待的时候:

RESPOND SENT
ITERATION COMPLETED

1 个答案:

答案 0 :(得分:-1)

您必须重写函数以返回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))