Martin Carre
Martin Carre

Reputation: 1249

Waiting for 2 promises to come back to use simultaneously in a function

First-off: I hope my question has not already been asked and answered elsewhere... I've been looking SO and the web on that and I can't seem to find anything (maybe it's not even possible).

Basically, I'm trying to build a DB (in my case with Mongo) get info from an webAPI (the crypto exchange Kraken). The objective is to build my collections with various objects that I get from requests.

Here the gitub repo: MongoNode

Here's the current code (I'm using simple callbacks and request at the moment: chaining up everything):

// External Modules
var request = require('request');
var yargs = require('yargs');
var _ = require('underscore');
var async = require('async');
var MongoClient = require('mongodb').MongoClient,
  co = require('co'),
  assert = require('assert');

// Own Modules

// Variables
var tickerArr= []

// Generator function for connection
co(function*() {
  // Connection URL
  var url = 'mongodb://localhost:27017/CryptoDB';
  // Use connect method to connect to the Server
  var db = yield MongoClient.connect(url);

  // Inside the DB connection
  console.log('Connection up and running...');

  // Getting the list of the tickers for USD and EUR exclusively
  request({
    url:'https://api.kraken.com/0/public/AssetPairs',
    json: true
  }, (error, response, body) => {
    var jsonObject = body;
    _.map(jsonObject, function(content) {
      _.map(content, function(data) {
        if(data.altname.indexOf('EUR') !== -1 || data.altname.indexOf('USD') !== -1)
          tickerArr.push(data.altname);
      });
    });
    // Getting the ticker info for each USD && EUR ticker available
    async.forEach(tickerArr, (item) => {
      request({
        url:`https://api.kraken.com/0/public/Ticker?pair=${item}`,
        json: true
      }, (error, response, body) => {
              db.collection('Assets').insertOne(
                body.result,
                request({
                      url:'https://api.kraken.com/0/public/Time',
                      json: true
                    }, (error, response, body) => {
                        return body.result;
                    })
                  );
              console.log('Asset Added!', body.result);
      });
    });
  });
  // Closing the DB connection
  // db.close();
  }).catch(function(err) {
  console.log(err.stack);
});

I've trying to use promises chaining 'em up as well but can't seem to find a way for it to work. Here's my promise playground:

var somePromise1 = new Promise((resolve, reject) => {
  resolve('Hey! It worked!');
});

var somePromise2 = new Promise((resolve, reject) => {
  resolve('Hey! It worked the second time!');
});

somePromise1.then(somePromise2.then((message1, message2) => {
  console.log('Success', message1, message2);
})
);

and here's what it print in the console when executed:

$Success Hey! It worked the second time! undefined

Thanks in advance for your help and I hope the question hasn't been answered already a million times!

Upvotes: 1

Views: 84

Answers (1)

marzelin
marzelin

Reputation: 11620

var somePromise1 = new Promise((resolve, reject) => {
  resolve('Hey! It worked!');
});

var somePromise2 = new Promise((resolve, reject) => {
  resolve('Hey! It worked the second time!');
});

somePromise1.then((message1) => somePromise2.then((message2) => {
  console.log('Success', message1, message2);
})
);

Promises are quite convoluted though. async/await makes things a lot clearer:

var somePromise1 = new Promise((resolve, reject) => {
  resolve('Hey! It worked!');
});

var somePromise2 = new Promise((resolve, reject) => {
  resolve('Hey! It worked the second time!');
});


async function exec() {
  const message1 = await somePromise1
  const message2 = await somePromise2
  console.log('Success', message1, message2);
}

exec()

Upvotes: 3

Related Questions