A
A
Arthur2019-08-30 16:56:52
Node.js
Arthur, 2019-08-30 16:56:52

How to make a function that returns the value received from https.request?

Greetings.
Tell me, please, to a person who is used to synchronous code, how to return a value in JS?
There is an algorithm in which I go over the users and call a certain method on them:

async function checkAll() {
  ...
  for (let i in users) {
    if (users[i].check()) {
      users[i].checked = true
      await users[i].save()
    }
  }
  ...
}

Here is the check method which is called
Schema.methods.check = async function () {
  const req = https.request(options, (res) => {
    res.on('data', (d) => {
      // Как тут сделать return для родительского метода?
    });
  });
  req.on('error', (e) => {
    console.error(e.message);
  });
  req.end();
}

Inside the users[i].check() method, I need to make a request to an external address, wait for it to complete, and return the result. In the dock, I see only how to hang up a function on the event.
It comes to mind only as an argument to pass a function to the check() method that does what I need, but something tells me that there is some more convenient method (like the await construct, which waits for the result).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ivandao, 2019-08-30
@ar2rsoft

Promisification

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question