0

I'm trying to make a function that gets data from CoinMarketCap API. For some reason the function kept getting called last of the script. Below is the entire code I've written.

const axios = require('axios');

let promise = new Promise(async (resolve, reject) => {

    let response = null;

    try {
        response = await axios.get('https://sandbox-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest', {
            headers: {
            'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c',
            },
            params: {
            'id' : 1,
            }
        });
    } catch(ex) {
    // error
        response = null;
        console.log(ex);
        reject(ex);
    }
    if (response) {
    // success
       const json = response.data;
       resolve(json);
    }
});

console.log("HI1");

promise.then((data) => {
    console.log(data);
}).catch(err => {
    console.log(err);
});

console.log("HI2");

When ever I run it it will result like this:

HI1
HI2
{dataFromPromiseFunction}
  • 2
    Of course it does: your promise runs on a separate "thread" in a way. The console.log statements are run at runtime. The promises have to wait for the axios promise to be resolved. If you want them to be in the order of `H1-{data}-H2`, then you need to use async/await – Terry Sep 21 '22 at 12:24
  • `new Promise(async (resolve, reject) => ` using a promise constructor with an async/await construct makes no sense. – Keith Sep 21 '22 at 12:29
  • @Keith removing the async/await results in {dataFromPromiseFunction} becoming undefined. I've written the promise function similarly to the one written in the CoinMarketCap API documentation. I'm still quite new to API calls and promise so I don't really know how this works. – Enrique Heryanto Sep 21 '22 at 12:36
  • That's likely because you are not returning anything,. eg. `return response`. – Keith Sep 21 '22 at 12:41

0 Answers0