0

I have a function that uses the request-promise module to scrape and parse HTML from a website. I want the function to just return some JSON data when it's done, and not a promise.

Here's the slimmed down version of the code I have so far:

const rp = require('request-promise');
const URL = 'http://example.com/';

async function get_data() {
    let get_data_wrapper = (async () => {
        let html = await rp(URL);
        let var1 = {};

        // Do stuff so that var1 contains JSON data

        return var1;
    });

    return await get_data_wrapper();// Return courses promise
}

Preferably, I would like to have get_data() return just the JSON data, as opposed to a promise.

Am I thinking about all this in the wrong way?

  • 1
    `async` functions always return a promise, you can't return JSON, instead the JSON will will be returned when the promise resolves. – Addis Mar 19 '20 at 22:37

2 Answers2

1

i believe you think this too complicated:

const rp = require('request-promise');
const URL = 'http://example.com/';

async function get_data() {
    let html = await rp(URL);
    let var1 = {};

    // Do stuff so that var1 contains JSON data

    return var1;
}
ZPiDER
  • 3,748
  • 1
  • 15
  • 15
  • @StricklyNoLollygagging - Just realize that `get_data()` still returns a promise. That promise will resolve to `var1` when you use `.then()` or `await` on that promise. While, it looks like `var1` is being returned directly from `get_data()`, it is not because it's `async`. In reality, as soon as you did `await rp(URL)`, `get_data()` returned a promise and when you did `return var1`, that promise got resolved with that value. That's how `async` functions work. – jfriend00 Mar 20 '20 at 00:38
1

get_data().then((res)->console.log(res));

NOT: const res=get_data() console.log(res)

Hope that helps!