L
L
lex2016-09-27 00:57:31
JavaScript
lex, 2016-09-27 00:57:31

callback request node js how to get data of this method in requeste?

Good time of the day, ladies and gentlemen)
I recently switched to node js and I haven’t been programming for so long and obviously I can’t understand something from the textbook.
I use node + ym and I can't figure out how to send data after request inside a module method

modules.define('clients', function(provide){

  provide({

    getClients: function(){

      /* Получаем список суб-клиентов агенства (или представителей) */

        var sendQ = {
           "method": "GetClientsList",
           "token": ""
        };

        var options = {
          url: "САЙТ",
          method: "POST",
          headers: {
              'Content-Type': 'application/json; charset=utf-8',
              'Authorization': 'Bearer'
          },
          json: true,
          body: sendQ
        };

        var clients = '';

        request(options, function (err, res, body) {
          var clients = body["data"];
          var client = clients.map(function(a){
            return a.Login;
          });
          // console.log(body);

          if(client[0] != false){
            console.log('Client list getty - OK - '+client[0]);
          }else {
            console.log('some problems');
          };
          return
        });

      return

      /* Список получен переходим к дальнейщим действиям */
    }

  });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2016-09-27
bem @bemdev

Firstly, if request is a module of the same name from npm, then it passes Buffer to the body parameter, if there is json, then it must be parsed var clients = JSON.parse(body.toString()).data
Secondly, the request itself is asynchronous, the easiest way is to wrap it in a promise, in total there will be something like this:

modules.define('clients', function(provide){

  provide({

    getClients() { //неименнованные функции - плохо для отладки, поэтому меняем на es2015 метод

      /* Получаем список суб-клиентов агенства (или представителей) */

        var sendQ = {
           "method": "GetClientsList",
           "token": ""
        };

        var options = {
          url: "САЙТ",
          method: "POST",
          headers: {
              'Content-Type': 'application/json; charset=utf-8',
              'Authorization': 'Bearer'
          },
          json: true,
          body: sendQ
        };

        //удалить, оно тут не надо
        //var clients = '';

        return new Promise((resolve, reject) => request(options, (err, res, body) => {
          if(err) {
            return reject(err); //прокидываем ошибку в промис
          }
          var clients = JSON.parse(body.toString()).data;
          var client = clients.map(a => a.Login);

          if(!client[0]) {
            console.log('Client list getty - OK - ' + client[0]);
            resolve(client[0]); //возвращаем client[0] из промиса
          } else {
            console.log('some problems');
            reject(new Error('some problems'));
          };
        })).then(client => {
      /* Список получен переходим к дальнейщим действиям */
        }).catch(err => {
          /* здесь обрабатываем ошибку */
        });
    }
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question