简体   繁体   中英

request-promise always returns response instead of returned value

I want to pass a variable defined inside request-promise to a variable out of scope. I thought I may pass the variable using a return statement inside the request function, but the request function always returns the http response (in this case as HTML output).

My code:

require('dotenv').config();
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
var request = require('request-promise');

var get = function(arg1, arg2, arg3, arg4) {
    request(`https://www.googleapis.com/customsearch/v1?key=${process.env.API_KEY}&cx=${process.env.CX}&q=${arg1}`, async function(err, res, body) {
        var obj = JSON.parse(body);
        var url =  obj.items[0].formattedUrl;
        var part = await request(`${url}/staffel-${arg2}/episode-${arg3}`, function(err, res, body) {
            const dom = new JSDOM(`${body}`);
            var part = dom.window.document.getElementsByClassName(arg4)[0];
            return part;
        });
        console.log(part);
    });
};

Furthermore, I'd like to pass the output to the get-function using return statements. Is there any way to do so?

Edit: From my point of view, this is not a duplicate of this question . The request returns a value, but it's not the value I want to return as explained above.

I guess your implementation is not perfect for request-promise with async await. didn't run the code but try below one.

async function asyncCall(arg1, arg2, arg3, arg4){
    try{
        var first = await request(`https://www.googleapis.com/customsearch/v1?key=${process.env.API_KEY}&cx=${process.env.CX}&q=${arg1}`);
        if(typeof first.body === "string"){
            first.body = JSON.parse(first.body);
        }
        var obj = first.body;
        var url =  obj.items[0].formattedUrl;
        var part = await request(`${url}/staffel-${arg2}/episode-${arg3}`)
        if(typeof part.body === "string"){
            part.body = JSON.parse(part.body);
        }
        var dom = new JSDOM(`${JSON.parse(part.body)}`)
        return dom.window.document.getElementsByClassName(arg4)[0];
    }
    catch(e){
        console.log(e);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM