C
C
CHILACE2017-03-05 08:20:50
In contact with
CHILACE, 2017-03-05 08:20:50

How to correctly return from a callback (webhook transformation)?

Good afternoon, dear ones.
I needed to somehow write a small script that converts requests from the VKontakte Callback API into the corresponding webhooks in the messenger used by our group. And, since I'm superficially familiar with programming, one question confuses me - which option is correct, "res.end('ok')" or "return res.end('ok')" at the bottom of the above example?
Both options work, but it seems to me that there is a pitfall here.

const http = require('http');
const jsonBody = require('body/json');
const request = require('request');
// ~~~
function mapWebhook(body) {
  // ~~~
  return options;
}
http.createServer(function(req, res) {
  jsonBody(req, res, function(err, body) {
    if (err) {
      res.statusCode = 400;
      return res.end(err.message);
    }
    if (body.type === 'confirmation') {
      return res.end(confirmToken);
    }
    let options = mapWebhook(body);
    request(options, function(error, response, body) {
      if (error) {
        res.statusCode = 500;
        return res.end(error.message);
      }
      return res.end('ok'); // Или "res.end('ok');"  ?
    });
  });
}).listen(8080);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yustas Alexu, 2017-03-05
@CHILACE

It's simple: if this is the last instruction in the function and the function should not return anything, then return is not necessary. If the callback is called somewhere in the middle or at the beginning, then it is better to return to be sure that after the callback is called, the function will not continue to be executed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question