hsel
hsel

Reputation: 163

Waiting for request to finish then go to next

How would I get this go through the getPrice then the getMarketCap function in order, so that it displays 'price searched, marketcap searched then searches complete'? I've looked at promises, but I'm unsure of how to use them in this case.

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

var parseBody1;
var price;

var parseBody2;
var marketCapUsd;

function getPrice(website) {
    rp(website)
        .then(function (body) {
            parseBody1 = JSON.parse(body);
            price1 = parseBody1[0]['price_usd'];
            console.log('price searched');
        });
}

function getMarketCap(website) {
    rp(website)
        .then(function (body) {
            parseBody2 = JSON.parse(body);
            marketCapUsd = parseBody2[0]['market_cap_usd'];
            console.log('marketcap searched');
        });
}

$('#search-button').click(function() {
    getPrice('https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=usd');
    getMarketCap('https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=usd');
    console.log('searches complete');

    console.log(price, marketCapUsd);
});

Upvotes: 0

Views: 58

Answers (3)

C.Dumange
C.Dumange

Reputation: 128

You have to use async/await with promises. It emulates synchronous behaviour.

Here are some examples: http://thecodebarbarian.com/common-async-await-design-patterns-in-node.js.html

Upvotes: 0

Shivam
Shivam

Reputation: 3642

The functions getPrice and getMarketCap should be returning promises. Since you are already using request promise you could simply return it,

Something like

function getPrice(website) {
    return rp(website)
    .then(function (body) {
        parseBody1 = JSON.parse(body);
        price1 = parseBody1[0]['price_usd'];
        console.log('price searched');
    });
}

Also you are calling them synchronously, so getMarketCap will not wait for getPrice to complete.

In order to achieve a serial flow. You should be calling getMarketCap only post getPrice is complete.

Something like

getPrice('https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=usd')
.then(() => {
   return getMarketCap('https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=usd');
})

Upvotes: 1

Rahul Sharma
Rahul Sharma

Reputation: 10111

try this

$('#search-button').click(function() {
    Promise.all([
        rp('https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=usd'),
        rp('https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=usd')
    ]).then((result)=>{
        parseBody1 = result[0];
        parseBody2 = result[1];
        price1 = parseBody1[0]['price_usd'];
        marketCapUsd = parseBody2[0]['market_cap_usd'];
        console.log('searches complete');
        console.log(price, marketCapUsd);
    })
});

Upvotes: 0

Related Questions