A
A
Alexander2018-08-27 04:17:10
Node.js
Alexander, 2018-08-27 04:17:10

How to return the result of a request execution inside a NodeJS function?

The essence of the problem, there is a function:

function funcname (){
    request('https://site.ru', function (error, response, body) {
        return body;
    });
}

How to return its result to a variable?
For example:
var info = funcname();
* I simplified the code as much as possible, but the essence remains.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Gerasimov, 2018-08-27
@QcfgAlexandr

function funcname() {
  return new Promise((resolve, reject) => {
    request('https://site.ru', (err, res, body) => {
      if (err) {
        return reject(err);
      }

      return resolve([res, body]);
    });
  });
}

(async () => {
  const [res, body] = await funcname();
})();

A
Anton Spirin, 2018-08-27
@rockon404

Read about how to write asynchronous code correctly . You can return a Promise .

Example
function getSome() {
  return new Promise((resolve, reject) => {
      request('https://site.ru', function (err, res, body) {
        if (err) {
          reject(err);
          return;
        }

        resolve(body);
    });
  });
}

Использование в коде:
getSome().then(res => {
  // do something with res
}).catch(err => {
  // handle error
});

Использование в асинхронной функции:
async foo() => {
  const some = await getSome();
  // use some
}

There are a bunch of Promise-based wrappers for requers, such as request-promise .
Example using request-promise
const rp = require('request-promise');

const getSome = async () => {
  try {
    const body = await rp({ uri: 'https://site.ru', json: true });
    // do something other
    return body;
  } catch (err) {
    // handle error
    return err;
  }
}

Использование в коде:
getSome().then(res => {
  // do something with res
}).catch(err => {
  // handle error
});

Использование в асинхронной функции:
async foo() => {
  const some = await getSome();
  // use some
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question