簡體   English   中英

Node.js var不保存

[英]Node.js var does not save

好的,所以我有一個用於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"});
});

有幾種方法可以實際解決此問題...但是最快的方法是利用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) {

還建議通過在try{}catch(e){}包裝await來添加一些錯誤處理。

有關諾言的更多信息,請點擊此處:
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