1

I have an array of coins, which I get from a database query. I pass this array to a function that needs to do an API call for each coin to get the value.

The FOR loop like this below will result in: (

)

// for (let i =0; i <= coins.length-1; i++){
//             console.log(i);
//              await (this.coinRepository.getActiveCoinAsync(i.coinName)
//                 .then(response => {
//                     // console.log((response[0].price_eur))
//                     // console.log((result[i].amount))
//                     // console.log( value +(response[0].price_eur) * (result[i].amount))
//
//                     value = value +((response[0].price_eur) * (i.amount))
//                     console.log(value)
//
//                 })
//                 .catch(error => reject(error))
//             )
//         }

Result:

console.log(i)
console.log(i)
console.log(i)
value
value
value

I tried this below but it doesn't seem to execute any promises:

return new Promise((resolve, reject) => {
let value = 0;
let promises =[];
for (let i =0; i <= coins.length-1; i++){
    let promise =  (this.coinRepository.getActiveCoin(coins[i].coinName))
    promises.push(promise);
    console.log(promise);
}
console.log(promises);
Promise.all(promises)
   .then(results =>{
        console.log(results);
    })
   .catch(error => reject(error))

coinRepository.getActiveCoin

    getActiveCoin(coin) {
    return new Promise((resolve, reject) => {
        console.log(coin)
        request('https://api.coinmarketcap.com/v1/ticker/'+coin+'/?convert=EUR', function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve (JSON.parse(body));
            }else {
                reject(error);
            }
        })

    });
}
6
  • Looks alright to me. What is the out put of your console.log Commented May 9, 2018 at 0:11
  • Bitcoin Promise { <pending> } Ethereum Promise { <pending> } Stellar Promise { <pending> } Monero Promise { <pending> } NEM Promise { <pending> } Vechain Promise { <pending> } Waltonchain Promise { <pending> } [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ] Commented May 9, 2018 at 0:12
  • Your code looks fine. Could you edit your answer with the this.coinRepository.getActiveCoin method? My guess is that this method does not resolve. Commented May 9, 2018 at 0:19
  • @James added to OP Commented May 9, 2018 at 0:22
  • Is the if (!error && response.statusCode == 200) { conditional truthy? (Put a console.log(..);within it to check) Commented May 9, 2018 at 0:24

2 Answers 2

1

Your code looks fine. Everything will be resolved unless there's a bug in the code you haven't shown us.

In particular, .catch(error => reject(error)) looks fishy because reject isn't defined anywhere.

I've simplified your code below, it runs as expected.

let i = 0;

function getActiveCoin(coin) {
  console.log(`getActiveCoin("${coin}")`);
  return new Promise((resolve, reject) => {
    resolve(`${coin} ${++i}`);
  });
}

let coins = [{
  coinName: "Bitcoin"
}, {
  coinName: "Stellar"
}];
let value = 0;
let promises = [];
for (let i = 0; i <= coins.length - 1; i++) {
  let promise = getActiveCoin(coins[i].coinName)
  promises.push(promise);
}
console.log('Promise.all');
Promise.all(promises)
  .then(results => {
    console.log(results);
  })

Sign up to request clarification or add additional context in comments.

3 Comments

my bad, the code that executes the promises is a promise itself. wil edit in OP
@AchielVolckaert Promise.all returns a new Promise already. Just return that instead of wrapping it with another new Promise(...). If any of the sub-promises reject, Promise.all will reject.
somehow it works with a function, but not from my repo class. code 100% same, except that getActiveCoins is in another class
0

My guess is that when you call reject reject does not exist, thus throwing an error that never gets called. Perhaps you meant:

let value = 0;
let promises = [];
for (let i =0; i <= coins.length-1; i++){
  let promise = this.coinRepository.getActiveCoin(coins[i].coinName)
  promises.push(promise);
}

Promise.all(promises)
    .then(results => console.log(results))
    .catch(error => console.error(error))

Edit 1: you do not explicitly reject on error in getActiveCoin(coin): this means that if you get an error, your promise will never resolve.

 return new Promise((resolve, reject) => {
    request('https://api.coinmarketcap.com/v1/ticker/'+coin+'/?convert=EUR', function (error, response, body) {
        if (error || response.statusCode != 200) {
            return reject()
        }

        resolve (JSON.parse(body));
    })
  })

6 Comments

this is a step in the right direction, but it still does not execute the array of promises
@AchielVolckaert Promises aren't "executed". Does getActiveCoin really return a Promise or does it return a function that returns a Promise?
@mpen added it to OP
Edited the answer. Added another clue as to why your code is probably stalling the way it is stalling now.
added it, should be there in the first place, but not the issue. the console.log doesn't even execute
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.