0

flagged as issue with asynchronous call, however call completes prior to final few lines of code, do not understand how that caused the issue?

I am a beginner to Javascript attempting to code a bot for discord. I have encountered another problem that I have spent days trying to fix. Please can someone tell me why my code is throwing this JSON undefined error?

function search(msg) {

    const puppeteer = require('puppeteer');

    let scrape = async () => {

        const browser = await puppeteer.launch({headless: false});
        const page = await browser.newPage();

        await page.goto(msg);

        const result = await page.evaluate(() => {
            let data = []; // Create an empty array that will store our data

                let ingredients = document.querySelector("ul li").innerText; // Select the ingredients
                let level = document.getElementsByTagName("p").innerText; // Select the level

                data.push({ingredients, level}); // Push an object with the data onto our array

            return data; // Return our data array
        });

        browser.close();
        return result; // Return the data
    };

    scrape().then((value) => {
        return value; // Success!
    });
};
var prep5 = search(prep4); //prep4 is a variable string providing a URL, testing with "https://ffxiv.consolegameswiki.com/wiki/Crab_Oil"

var obj = JSON.parse(prep5);

console.log(obj.ingredients + ' and ' + obj.level);

I see puppeteer successfully open the webpage, then close itself on a completed load, and would expect in this case to see "2 Water Shard, 2 Megalocrab Leg and Level 26 Alchemist" output to the console, however all I get is

"SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse ()"

EDIT: quick link to reference page - https://ffxiv.consolegameswiki.com/wiki/Crab_Oil

Richard Goodman
  • 101
  • 1
  • 1
  • 8
  • my understanding was that from this code the array I create in data gets output as JSON in prep5 - is that not the case? – Richard Goodman Jul 18 '19 at 14:48
  • My bad, I completely mis-read the code. Although as a terminology thing you're not "getting the output as JSON", it's an object. – Dave Newton Jul 18 '19 at 14:49
  • no problem, I was more double-checking, its the first time i've tried to do anything like this. I see, so the output object would be in JSON format rather? – Richard Goodman Jul 18 '19 at 14:50
  • 1
    The output object would be an object. – Dave Newton Jul 18 '19 at 15:00
  • @Quentin reading through the information provided about Async (thanks for the link, really helpful), I take it I'm just missing an "await" call before my search function at prep 5? – Richard Goodman Jul 18 '19 at 15:09

0 Answers0