Answer the question
In order to leave comments, you need to log in
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
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.
Разобраться как работает асинхронный код. Поставить return в нужном месте и наслаждаться.
Пример использования дан сразу на главной странице request'a
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // здесь точно уже есть данные
}
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question