0

好的,所以我有这个 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"});
});
4

1 回答 1

0

有几种方法可以实际解决这个问题……但最快的方法是使用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) {

还建议通过awaittry{}catch(e){}.

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

于 2017-12-22T22:58:12.677 回答