These are chat archives for rosshinkley/nightmare

28th
Nov 2016
Ændrew Rininsland
@aendrew
Nov 28 2016 17:39
Hey all — quick question, what’s the best way to use Nightmare with async/await? I've noticed if you call .then() before .end() bad stuff happens, but how do you not effectively call .then() when you await?
Rob Brackett
@Mr0grog
Nov 28 2016 19:00

@aendrew If you are using await, you don't need to use then at all. If you have an await function like:

async function doSomething () {
  await someOtherAsyncThing();
  return doSomethingElse();
}

What it is actually doing is basically:

function doSomething () {
  return new Promise((resolve, reject) => {
    someOtherAsyncThing().then(() => {
      const returnValue = doSomethingElse();
      resolve(returnValue);
    });
  });
}

At the end of the day, async/await is a nicer way to write promise code that automatically calls then for you :)

So! Nightmare code with async/await is just like generators:

async function scrapeAPage() {
  const headline = await Nightmare()
    .goto('http://somewhere.com')
    .title()
    .end();
  return headline;
}