variable not assigning inside promise

By | July 17, 2018
Questions:

Maybe I’m sleepy, but under what circumstances would the following occur?

let foo;

page
  .evaluate(() => {
    // return works... but not closure assignment

    // doesn't work
    foo = 'foo';

    // works
    return 'bar';
  })
  .then(bar => {
    console.log('foobar', foo, bar);
    // > foobar undefined bar
  });

This is occurring in a mocha test using puppeteer

update: the exact entire code

node 9.11.2

/* global describe, it, before, after */

const fs = require('fs-extra');
const path = require('path');
const assert = require('assert');
const puppeteer = require('puppeteer');
const sleep = require('shleep');

const extPath = path.resolve(__dirname, '..', 'build');
const { name } = fs.readJSONSync(path.resolve(extPath, 'manifest.json'));

// Access chrome object in Extensions
// https://github.com/GoogleChrome/puppeteer/issues/2878

describe('chrome extension', () => {
  let browser;
  let extensionPage;

  before(async function() {
    this.timeout(90 * 1000);

    // start puppeteer
    browser = await puppeteer.launch({
      headless: false,
      args: [
        `--disable-extensions-except=${extPath}`,
        `--load-extension=${extPath}`
      ]
    });

    // poll instead of hope this is enough time?
    const EXT_LOAD_DELAY = 100;
    await sleep(EXT_LOAD_DELAY);

    const targets = await browser.targets();

    const extensionTarget = targets.find(
      ({ _targetInfo }) =>
        _targetInfo.type === 'background_page' && _targetInfo.title === name
    );

    const page = await extensionTarget.page();

    let foo;

    page
      .evaluate(() => {
        // return works... but not closure assignment

        // doesn't work
        foo = 'foo';

        // doesn't log
        console.log('foo', foo);

        // works
        return 'bar';
      })
      .then(bar => {
        console.log('foobar', foo, bar);
        // > foobar undefined bar
      });
  });

  it('should load', async () => {
    assert(true);
  });
});

screenshot of test

enter image description here

Answers:

Leave a Reply

Your email address will not be published. Required fields are marked *