我被困在代码中,我尝试了其他方法来等待node.js中的写入文件,但它没有等待。
下面是代码
app.post('/createEmp',async (req,res) => {
console.log("Inside createEmp()");
var response = await createEmp(req.body);
console.log(response);
});
async function createEmpFile(fileContentObj){
var response = {};
console.log("filePath :"+filePath);
return new Promise(function(resolve,reject){
fs.writeFile(filePath, fileContentStr, function (err) {
if (err){
console.log("err :"+err);
reject(err);
}
else {
console.log('Saved!');
fileSavedFlag = true;
response.result = fileSavedFlag;
console.log(response);
resolve(response)
};
});
}); // end of promise
/*return new Promise(function(resolve,reject) {
const file = fs.createWriteStream(filePath)
file.write(fileContentStr)
file.end();
file.on("finish", () => { fileSavedFlag = true; resolve(response) });
file.on("error", () => { resolve(response) });
}); */
}
在节点js控制台上,我可以看到响应,但是当我使用邮递员打电话时,没有得到任何响应
答案 0 :(得分:0)
您的发布路线应具有res.send
如下
app.post('/createEmp',async (req,res) => {
console.log("Inside createEmp()");
var response = await createEmp(req.body);
console.log(response);
res.send(response)
});