Q
Q
qunaxis2016-08-19 18:17:10
JavaScript
qunaxis, 2016-08-19 18:17:10

Return is executed before receiving data using request, how to overcome it?

When request.get is wrapped in a function, return is executed before the response from the server arrives.
I tried to put return inside request.get, and after it, the result is the same - first undefined comes, then the server response is written through console.log.
How to solve the problem?

function yandex(text) {
    request.get(
        {
            url: 'https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20160818T135029Z.c4e26ce1f155163d.16a9ae1dfc2a21d21e64111ee1b0689a8c77d61b&lang=en-ru&text=' + text,
            json: true
        },
        function (error, response, body) {
            if (error) {
                console.error(error);
            } else {
                console.log(body.text[0]);
            }
        }
    );
}

console.log(yandex('test'));

Как изменить этот код для того, чтобы всё работало как надо?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Тимур Шемсединов, 2016-08-19
@qunaxis

Read about asynchronous programming in Node.js. All functions that contain asynchronous input/output must be asynchronous, i.e. return values ​​via callback, and they don't need return at all. See examples: https://github.com/HowProgrammingWorks/Asynchronou... and here https://github.com/DzyubSpirit/Asynchronous-Javascript there are many pages with getas.

O
Oleg, 2016-08-19
@werty1001

Use callback

Максим, 2016-08-19
@maxfarseer

Разобраться как работает асинхронный код. Поставить return в нужном месте и наслаждаться.
Пример использования дан сразу на главной странице request'a

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // здесь точно уже есть данные
  }
})

Николай Антонов, 2016-08-19
@my-nickname

async/await или promise

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question