LubieCiastka
LubieCiastka

Reputation: 143

how to deal with node.js promise

I started the adventure with node js. I'm overwhelmed by the promis and the promis using modules.

Can someone explain to me step by step what's going on in the code and how to pass the data further using promise ? Do you know any good tutorial or article where it is described and outlined?

Does promis have different syntax depending on the module?

I used the bluebird and my code to retrieve data from the API looks like this:

const Promise = require('bluebird');
const rp = require('request-promise');

let hello = "Hello";
console.log(hello);

const options = {  
    url: 'https://bitbay.net/API/Public/BTCUSD/orderbook.json',
    method: 'GET',
    headers: {
    'Accept': 'application/json',
    'Accept-Charset': 'utf-8',
    },
    json: true
};

let promise = Promise.resolve();

promise = promise.then(() => {
    let p1 = rp(options);
    let p2 = rp(options);
    let p3 = rp(options);

    return Promise.all([p1,p2,p3]);
});
promise = promise.then(([p1, p2, p3]) => {
    console.log(response);

    return 'works';
});
promise = promise.then((x) => {
    console.log(x);
})

Now I wanted to use the database so I wrote something like this:

const Promise = require('bluebird');
const mysqlssh = require('mysql-ssh');

mysqlssh.connect(
    {
        host: '****',
        user: '****',
        password: '*****!'
    },
    {
        host: '127.0.0.1',
        user: '****',
        password: '****',
        database: '****'
    }
)
.then(client => {
     client.query(`SELECT $ FROM users`, function (err, results, 
fields) {
     if (err) throw err;
     console.log(results);
     mysqlssh.close()
})
client.query(query, function (err, results, fields) {
    if (err) throw err;
    console.log(results);
    console.log(results[0]['BTC_turnover']);
    mysqlssh.close()
    })
})
.catch(err => {
    console.log(err)
})

I do not know how to join it. Download the data first, then ask the base and then something further.

Upvotes: 0

Views: 159

Answers (1)

Zac Delventhal
Zac Delventhal

Reputation: 4010

So, first, Promises are reasonably simple little objects that replace the need for callbacks. When the asynchronous operation completes they pass the result to a then method if everything worked, or a catch method if something broke.

// This function using a callback is equivalent to 
// the following function which uses a Promise
asyncFn((err, result) => {
    if (err) throw err
    console.log(result)
})

asyncFn()
  .then(result => { console.log(result) })
  .catch(err => { throw err })

Promises are particularly nice when you have many asynchronous functions in a row. With callbacks, you would have to nest them and it would get very difficult to read. With Promises you can just keep adding then methods to the end without nesting.


Next, there are a few Promise libraries out there, and they differ in some features, but their core behavior is identical. You should be able to use them pretty interchangeably. Also, remember that Promises are just objects. In your example code you are working with the Promise returned by mysqlssh.connect, which is a native Promise. The fact that you happened to import bluebird in your code won't change what object gets returned.


Okay, the final thing worth noting, is that while mysqlssh.connect returns a Promise, the client you get is a mysql2 connection. It's a completely different library that does not use Promises. This is why you need to pass a callback into client.query. You can mix Promises and callbacks fine, but the normal rules apply to your callbacks: you must nest them if you want to wait on the results of the first before calling the next.

Right now, you are firing them both off independently. The results of one have no way of interacting with the results of the other, and even worse, whichever one happens to finish first is going to close the db connection before the slower one finishes! Rewrite your queries nested like this:

client.query(`SELECT $ FROM users`, function (err, userResults, userFields) {
    if (err) throw err;
    console.log(useResults);

    client.query(query, function (err, results, fields) {
        if (err) throw err;
        console.log(results);
        console.log(results[0]['BTC_turnover']);

        // Insert any joining of userResults, userFields, results, and fields here

        mysqlssh.close()
    })
})

Upvotes: 1

Related Questions