Answer the question
In order to leave comments, you need to log in
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;
});
}
var info = funcname();
Answer the question
In order to leave comments, you need to log in
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();
})();
Read about how to write asynchronous code correctly . You can return a Promise .
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
}
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 questionAsk a Question
731 491 924 answers to any question