简体   繁体   English

Node.js var不保存

[英]Node.js var does not save

ok so i have this code for a Microsoft QnA Bot, i have that let message variable global and i need to save it.Problem is it does not...if i run a console.log inside the function on message everything is fine but outside the message is back to normal...What am i suppose to do?Thank you! 好的,所以我有一个用于Microsoft QnA Bot的代码,我让消息变量设置为全局变量,我需要保存它。问题是它不是...如果我在消息上的函数内运行console.log,一切都很好但是消息以外的消息恢复正常...我该怎么办?谢谢!

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"});
});

There are a few ways to actually fix this...but the quickest way is to utilize async/await . 有几种方法可以实际解决此问题...但是最快的方法是利用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"});
});

Changes: 变化:

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

and

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

It's also recommended to add some error handling with this process by wrapping the await within a try{}catch(e){} . 还建议通过在try{}catch(e){}包装await来添加一些错误处理。

More info on promises here: 有关诺言的更多信息,请点击此处:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM