F
F
fraps012019-09-22 15:57:07
JavaScript
fraps01, 2019-09-22 15:57:07

How to remember the text that is executed in the function?

var request = require("request");
function more() {
var url = "...";  //... - сайт, к которому выполняется реквест
request(url, function(error, response, body) { 
return body; // body - текст, который выводит сайт
});
};

You need to remember this text, write it to a variable for further use.
But if we write this function into a variable, then every time this variable is called, the function will be executed, that is, the request
Example

more()[0];
Сначала он выполнит реквест, потом выведет результат

Can this be avoided somehow? This function needs to be called only once a day, in other cases we only access the variable.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2019-09-22
@fraps01

The main problem with getting body is that request is asynchronous. That is, the answer will not come immediately, but after some time, while js will not wait for this answer, but will continue to execute the code after the request. This, in turn, will lead to the fact that in this code we cannot receive a request response, this happens because the response has not yet arrived)
How to be in this situation ???
Read about asynchrony , promises and async / await
Next, I give a simple class that can cache requesta responses, and an example of its use:

var request = require("request");


// создаем класс для кэширования результатов запросов
class СacheRequest {
  // конструктор
  constructor(handler){
    // создаем ассоциативный массив для кэширования результата
    this.cache = {};
  }
  
  // основной метод класса, предназначен для получения данных по ссылке
  // принимает url в качестве параметра
  // возвращает выполненный промис если запрос есть в кэше
  // или промис в ожидании выполнения запроса
  async get(url){
    // если такой запрос уже был, возвращаем промис с результатом из кэша
    if( this.cache[url] )
      return  Promise.resolve(this.cache[url]);
    
    // иначе возвращаем промис с ожиданием результата
    return new Promise((resolve,reject)=>{
      // делаем запрос на указаный url
      request(url, (error, response, body)=>{
        // если ошибка - реджектим )
        if( error )
          return reject(error);
        
        // иначе запоминаем в кэше ответ
        this.cache[url] = body;

        // и резолвим body
        resolve(body);
      });			
    });
  }

  // метод отчищает кэш
  clear(){
    this.cache = {};
  }
}

// создаем экземпляр кэша
const cacheRequest = new СacheRequest();

// так как request асинхронный, то для того, чтобы получить 
// результат запроса в "синхронном стиле" используем await

// await можно использовать только внутри асинхронной функции.
// для этой цели обернем блок с вызовами cacheRequest.get в
// само вызывающуюся асинхронную функцию
(async () => {
  // выполняем запросы:
  // запросим "http://google.ru/" (будет сделан фактический запрос)
  let body = await cacheRequest.get("http://google.ru/");
  console.log("\n\n\nBODY:", body, 111);

  // еще раз запросим "http://google.ru/" (будет взято из кэша)
  body = await cacheRequest.get("http://google.ru/");
  console.log("\n\n\nBODY:", body, 222);
})()

// раз в сутки отчищаем кэш
setTimeout(()=>{
  cacheRequest.clear();
}, 1000*60*60*24 ); // 1000*60*60*24 это количество миллисекунд в сутках

A
Anton Neverov, 2019-09-22
@TTATPuOT

Declare a variable outside of the function. Implementation example:

let exemple;

const updateExempleValue = () => {
    if (exemple === undefined) { //Если переменная undefined то в любом случае стучимся к серверу
        exemple = 'ok'; //Здесь ваша фукцния по заданию переменной, вмето 'ok'.
    }
    return exemple; //Возвращаем переменную
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question