B
B
babbert2019-04-11 09:07:48
Node.js
babbert, 2019-04-11 09:07:48

How to convert asynchronous code to synchronous?

Hello. I'm currently trying to use the PhantomJs wrapper for node - horseman .
Here is an example code:

const Horseman = require('node-horseman');
const users = ['PhantomJS', 'nodejs'];


users.forEach((user) => {
    console.log(5)
    const horseman = new Horseman()
      .open(`http://twitter.com/${user}`)
      .text('.ProfileNav-item--followers .ProfileNav-value')
      .click('a')
      .then((text) => {
        console.log(6);
      })
      .close();
});

Gives me:
5
5
6
6

But you must:
5
6
5
6

That is to make this code synchronous.
Hope for help here.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Drozdov, 2019-04-11
@babbert

Before it's too late, try not to use PhantomJs (it is no longer particularly supported), there is https://github.com/GoogleChrome/puppeteer from Google, it will be cooler)

R
Robur, 2019-04-11
@Robur

you can make it synchronous only if you remove everything asynchronous (horseman), but then this code will be useless.
What you need is not synchronicity, but correct order.
Use either promise chaining or async/await in the loop instead of forEach (if phantomjs supports it).

E
Eugene, 2019-04-11
@Shagfey

Use async / await.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question