question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

awaitPromise causing error on evaluating promise

See original GitHub issue
Component Version
Operating system Windows 10
Node.js 8.2.1
Chrome/Chromium/… Version 62.0.3173.2 (Official Build) canary (64-bit)
chrome-remote-interface 0.24.2

Is Chrome running in a container? NO

I have a node script I’m using to try and load up a form to be printed out as a PDF. This form requires headers and cookies to be set, as the user needs to be authorized. Additionally, once this form is “loaded”, there is data that is fetched at runtime to fill in. Therefore, I have a flag on the window that is set once everything is finished loading.
I’m attempting to use the Runtime.evaluate functionality with the awaitPromise: true option. However, here’s where things break with a Result of the evaluation is not a promise error.

First, if I don’t set the cookie, then my script will execute and I won’t the result error. However, since my form isn’t actually loaded up (I end up at a forbidden page), this isn’t desired.
Once I set the cookie, I get my result error. Now, sometimes (I’m debugging with VSCode) when I sit paused for a second or two before I evaluate my code, everything runs as expected. So I think there’s something to do with waiting for things to be loaded appropriately, but I can’t find any help/documentation on how to get around my issue.

Below is my script I’m using (certain parts stripped out for confidentiality).

const fs = require('fs');
const { URL } = require('url');

const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
const uuid = require('node-uuid');

const urlToLoad = new URL("https://site.com/form-to-show");
const csrfToken = uuid.v4();


async function readStdIn() {
    return new Promise((resolve) => {
        resolve("myAuthorizationToken"); //For testing purposes hard coded result
    });
}

async function launchChrome(headless = true) {
    return chromeLauncher.launch({
        chromeFlags: [
        '--disable-gpu',
        headless ? '--headless' : ''
        ]
    });
}

async function cbToPromise(cb) {
    return new Promise((resolve) => {
        cb((resp) => {
            resolve(resp);
        })
    });
};

const execute = async () => {
    return new Promise(async (resolve, reject) => {
        try {
            
            const authorizationToken = await readStdIn();

            const chrome = await launchChrome();
            const client = await CDP({port: chrome.port});

            const {Page, Runtime, Network, DOM} = client;

            await Page.enable();
            await Runtime.enable();
            await Network.enable();
            await DOM.enable();            

            const setHeaders = await Network.setExtraHTTPHeaders({'headers': {
                'Authorization': authorizationToken,
                'X-CSRF-Token': csrfToken
            }});
            const cookieSet = await Network.setCookie({url: urlToLoad.origin, name: 'CSRFToken', value: csrfToken});

            const navigated = await Page.navigate({url: urlToLoad.href});
            const loaded = await Page.loadEventFired();

            let js =  `
                new Promise((fulfill, reject) => {
                    setTimeout(() => {
                        fulfill('your result');
                    }, 1000); // simulate a long-running async operation
                })`;
            const result = await Runtime.evaluate({
                expression: js, //Just testing a simple promise at this point
                awaitPromise: true
            }); //Throws message: 'Result of the evaluation is not a promise'
            if (result.exceptionDetails && result.exceptionDetails.exception) {
                throw Error(result.exceptionDetails.exception.description); //Used for any invalid js execution
            }

            const pdf = await Page.printToPDF({});
            
            client.close().then(() => {
                chrome.kill().then(() => {
                    resolve(pdf.data);
                });
            });
        } catch (e) {
            reject(e);
        }
    });
}


execute().then(base64Data => {
    const buff = Buffer.from(base64Data, 'base64');
    fs.writeFileSync('test.pdf', buff);      

    process.exit(1);
}).catch(e => {
    console.error(e);
    process.exit(-1);
});

Am I missing something here? Seems broken…

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
ashumahercommented, Nov 2, 2017

const NativePromise = ((async function () {})().constructor);

0reactions
AStokercommented, Aug 2, 2017

I would have never thought about that 😄 I think I have a less hacky approach that we can use in our instance though, but I’ll stick that in my back pocket for later. I appreciate it.

Read more comments on GitHub >

github_iconTop Results From Across the Web

await not working in async promise node.js - Stack Overflow
I have this code in node.js with puppeteer with Axios that makes POST request, get the response and uses that response in puppeteer....
Read more >
JavaScript Promises and Errors - Peter Coles
You can use await inside an async function to automatically resolve a line as a promise (note: not needed in the final return...
Read more >
Handling those unhandled promise rejections with JS async ...
One of your await ed functions fails (i.e. rejects a promise); You get the error. Another possibility is that you know you need...
Read more >
Promise.all() - JavaScript - MDN Web Docs
The Promise.all() method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the ......
Read more >
Resolving the JavaScript Promise Error "TypeError: Cannot ...
TypeError: Cannot read property 'then' of undefined. In this guide, we will cover two code examples containing a bugs that cause this TypeError ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found