Monday 12 June 2017

Issue accessing value outside of a function that it is set in

I am having some issues working with the IBM Natural Language Understanding API. Everything is hooked up and logging in the console, so connection is working. However, I am having some issues accessing the data within my Express app.

I want to set req.body.sentiment to the value of response.sentiment.document.score (which is a value from the object passed back in the response from the nlu.analyze function (the Watson API)). I console.log response.sentiment.document.score and see the expected value displayed.

I have tried to comment what I am seeing. If I hard code req.body.sentiment = 0.98; - this sets the value to 0.98, which can be accessed in the view. However, when I set req.body.sentiment within the nlu.analyze function, it isn't available outside of the function. For example, when I log req.body.sentiment further down in the Promise - it returns either the original hardcoded 0.98 value or undefined (if I don't hardcode the value initially).

I feel as though I am missing something obvious, but can't put my finger on it. Help appreciated.

Controller:

const Post = require('../models/post');
const time_ago_in_words = require('time_ago_in_words');
const nlu = require('../config/watson.js');

...

function createPost(req, res, next) {

  console.log(req.body);

  req.body.createdBy = req.user;
  if(req.file) req.body.image = req.file.key;

  // Test to see check the req.body.sentiment syntax is correct.
  // This sets the value to 0.98, which can be accessed in the view
  req.body.sentiment = 0.98;

  // Passing in the body of the form to be analysed by IBM Watson
  const parameters = {
    'text': req.body.body,
    'features': {
      'sentiment': {},
      'emotion': {},
      'relations': {
        'limit': 5
      },
      'categories': {
        'limit': 5
      },
      'entities': {
        'emotion': true,
        'sentiment': true,
        'limit': 5
      }
    }
  };

// IBM WATSON analysis function
  nlu.analyze(parameters, function(err, response) {
    if (err) {
      console.log('error:', err);
    } else {

      // Logs 0.5467364 in the console - the value I am wanting
      console.log(response.sentiment.document.score);
      // Attempt to update req.body.sentiment to a new value
      req.body.sentiment = response.sentiment.document.score;
      // Logs 0.5467364 in the console - as though req.body.sentiment has been updated
      console.log(req.body.sentiment);
    }

  });



  Post
    .create(req.body)
    .then(() => {
      // Logs 0.98 in the console - the original value. Without initially setting this to 0.98, it returns undefined
      console.log('sentiment before redirect:', req.body.sentiment);
      res.redirect('/posts');
    })
    .catch((err) => {
      if(err.name === 'ValidationError') return res.badRequest(`/posts`, err.toString());
      next(err);
    });
}



via Tim Rooke

No comments:

Post a Comment