0

So I have this fetch-api

let test = () => fetch(usd_api).then(response => response.json())
.then(data => data.exchange_rates.dash_usd);

Console log

let console_test = () => {console.log(test())}

enter image description here

How can use this number [[PromiseResult]]: 134.445... in the following function where the number 150 is.

function main(){

         fetch(txs_api).then(response => response.json()).then(function(data) {
                
             var amount = data.txs[0].vout[1].value;
               
             if(amount == 150){
                // SUCCESS!
                $('#modal').modal('hide');
                console.log('requests stopped');
                clearInterval(interval);
             }
         })
}
Gass
  • 7,536
  • 3
  • 37
  • 41
  • @TusharShahi it gives me an error `test2:62 Uncaught ReferenceError: console_test is not defined at HTMLButtonElement.onclick` – Gass Jun 21 '21 at 10:58
  • 4
    `fetch` already returns a promise, wrapper promise constructor is not needed. – Yousaf Jun 21 '21 at 10:59
  • Use `async function console_test () {console.log(await test())}` – Krokodil Jun 21 '21 at 11:04
  • @Yousaf yes thanks – Gass Jun 21 '21 at 11:04
  • 1
    You can use `Promise.all` to make two parallel API calls and get both numeric values in an array: `Promise.all([fetch(...), fetch(...)]).then(...)` – Yousaf Jun 21 '21 at 11:05
  • What does `test` have to do with `comfirm_transaction`? The latter seems to work, no? – Bergi Jun 21 '21 at 11:10
  • @Bergi I need to work with the number that `test()` returns inside the `confirmation_transaction` function, where the if statement is. – Gass Jun 21 '21 at 11:19
  • @Gass In that case, you'll want to do `.then(function(data) { return test.then(function(exchangeRate) { … }); })` – Bergi Jun 21 '21 at 11:30
  • @Bergi could you please make this comment a detailed answer. I'm new to fetch and promises. – Gass Jun 21 '21 at 11:47
  • 1
    Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – FZs Jun 21 '21 at 17:04
  • @FZs Nope .. I tried but I had to many problems trying to understand it and apply it to my code, that's why I asked... But I figured it out with the help of everyone in this question. Thanks anyway. – Gass Jun 21 '21 at 17:17

3 Answers3

1
let test = () => fetch(usd_api)
  .then(response => response.json())
  .then(data => data.exchange_rates.dash_usd);

You want too keep using the same promise, if you want to log the result of your promise you need to wait for it to be completed:

// with .then()
test().then(console.log);

// or with await if you can:
console.log(await test());
kigiri
  • 2,952
  • 21
  • 23
0

I figured it out. Don't know if it's the best way to do it but it's working.

function main(){

  fetch(usd_api).then(response => response.json()).then(function(data) {
                        
      var dash_price = data.exchange_rates.dash_usd;
                    
      fetch(txs_api).then(response => response.json()).then(function(data) {
                    
          var amount = data.txs[0].vout[1].value;

          if(amount == dash_price){
              // SUCCESS!
              $('#modal').modal('hide');
              console.log('requests stopped');
              clearInterval(interval);
          }
      })
   })
}
Gass
  • 7,536
  • 3
  • 37
  • 41
-1

Do not return value. Because it returns to below function

function(data) {
  return data.exchange_rates.dash_usd
}

If you want to return your value to a variable you have to use Promise like below.

    let test = new Promise((resolve, reject) => {
        fetch(usd_api).then(response => response.json())
            .then(function (data) {
                resolve(data.exchange_rates.dash_usd) 
            });
    })
    
    async function demo(){
        let console_test  = await test
        console.log(console_test )
    }
    demo()

Note : Do not forget to use async and await

  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jun 21 '21 at 11:29
  • @Bergi. This is for demo. If you are not using fetch. You are simply using any calculation which take time. You can use promise. – Mukti Prasad Behera Jun 21 '21 at 11:31
  • 2
    The OP already uses promises and `fetch`. Their code for `test` is working. You should not use `new Promise`. – Bergi Jun 21 '21 at 11:33