How to access requested body from another function with async/await?

#1
Sorry for the generic title. I'm pretty new to nodejs as well as the idea of async/await.

So I have an express app, which makes an HTTP get request as a callback function. The callback function gets the body object, and returns it to getBody function. But when I try to assign getBody to a variable, it returns undefined.

Yes I know. The getBody function returns body before body gets filled up with data, but I just don't know how to write a getter method for this body object. So my question is, how can I run the get request and access body object in the global scope at the same time, so all functions depending on body object can run without further problems.

Mã:
async function getBody (req, res, next) {
    let body = await makeRequest(req, res);
    return body; // THIS RETURNS UNDEFINED

}

router.get('/', getBody);

function makeRequest (req, res){

    let uri;

    let options = {
        uri: uri,
    };

    request(options,  function (error, response, body) {
        if (error){
            console.log('error:', error);
        } else {
            console.log('Success! statusCode:', response && response.statusCode);
            let jsonObject =  JSON.parse(body);

            return jsonObject;
        }
    });
}
I did my research, but I just could not find a useful resource. Thanks in advance.
 

Admin

Administrator
Thành viên BQT
#2
await and async should be used with a promise, these kind of method cannot return data. return is used to return a value from a synchronous method.

So you may return a promise from your makeRequest method like this,

Mã:
async function getBody(req, res, next) {
    let body = await makeRequest(req, res);
    return body; // NOW BODY IS NOT UNDEFINED, call next() or send response here
}

router.get('/', getBody);

function makeRequest(req, res) {
    return new Promise((resolve, reject) => {
        let uri;

        let options = {
            uri: uri,
        };

        request(options, function (error, response, body) {
            if (error) {
                console.log('error:', error);
                return reject(error);
            } else {
                console.log('Success! statusCode:', response && response.statusCode);
                let jsonObject = JSON.parse(body);

                return resolve(jsonObject);
            }
        });
    })
}
FYI,
Mã:
let body = await makeRequest(req, next)
is equals to
Mã:
makeRequest(req, next).then(body => { /* YOUR CODE HERE */ })
and if you didn't knew, you have to process the body and send the response, return body won't send the response to the client.
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top