Node.js var 不保存

Node.js var does not save

好的,所以我有这个用于 Microsoft QnA Bot 的代码,我有那个 let message variable global 我需要保存 it.Problem 是不是...如果我 运行 a console.log 在 message 函数内部一切正常,但在消息外部恢复正常...我该怎么办?谢谢!

let message = "?"; ///my var global

app.post('/send',upload.any(),function (req,res,next) {
// Post event
    const translated = JSON.stringify({"question": req.body.message});
    const extServerOptionsPost = {
        host: 'westus.api.cognitive.microsoft.com',
        path: 'https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases//generateAnswer',
        method: 'POST',
        headers: {
            'Ocp-Apim-Subscription-Key': '',
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(translated)
        }
    };

    const reqPost = http.request(extServerOptionsPost, function (res) {
        console.log("response statusCode: ", res.statusCode);
        res.on('data', function (data) {
            process.stdout.write("JSON.parse(data).answers[0].answer"); 
            message = JSON.parse(data).answers[0].answer;
            console.log(message);//Everything is fine!
        });
    });
    reqPost.write(translated); // calling my function
    console.log(message)// not fine anymore :(
    res.render('Bot',{quote:"no question"});
});

有几种方法可以实际解决此问题...但最快的方法是利用 async/await

app.post('/send',upload.any(),async function (req,res,next) {
// Post event
    const translated = JSON.stringify({"question": req.body.message});
    const extServerOptionsPost = {
        host: 'westus.api.cognitive.microsoft.com',
        path: 'https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases//generateAnswer',
        method: 'POST',
        headers: {
            'Ocp-Apim-Subscription-Key': '',
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(translated)
        }
    };

    const reqPost = await http.request(extServerOptionsPost, function (res) {
        console.log("response statusCode: ", res.statusCode);
        res.on('data', function (data) {
            process.stdout.write("JSON.parse(data).answers[0].answer"); 
            message = JSON.parse(data).answers[0].answer;
            console.log(message);//Everything is fine!
        });
    });
    reqPost.write(translated); // calling my function
    console.log(message)// not fine anymore :(
    res.render('Bot',{quote:"no question"});
});

变化:

app.post('/send',upload.any(),function (req,res,next) {

app.post('/send',upload.any(),async function (req,res,next) {

const reqPost = http.request(extServerOptionsPost, function (res) {

const reqPost = await http.request(extServerOptionsPost, function (res) {

还建议在此过程中添加一些错误处理,方法是将 await 包装在 try{}catch(e){} 中。

更多关于 promises 的信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function