最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Node.js var不保存

运维笔记admin14浏览0评论

Node.js var不保存

Node.js var不保存

好吧所以我有这个代码的微软QnA机器人,我有让消息变量全局,我需要保存它。问题是它不...如果我在函数内运行一个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',
        path: '.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',
        path: 'https://westus.api.cognitive.microsoft/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) {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){}中来为此过程添加一些错误处理。

有关承诺的更多信息: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Statements/async_function

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论