在另一个函数的 if 语句中使用 fetch-api 的承诺结果 - JS

Use a promise result from a fetch-api in an if statement of another function - JS

所以我有这个提取-api

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

控制台日志

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

如何在数字 150 所在的以下函数中使用此数字 [[PromiseResult]]: 134.445...

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);
             }
         })
}
let test = () => fetch(usd_api)
  .then(response => response.json())
  .then(data => data.exchange_rates.dash_usd);

你也想继续使用同一个承诺,如果你想记录你的承诺的结果,你需要等待它完成:

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

// or with await if you can:
console.log(await test());

不要return值。 因为它 return 低于函数

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

如果你想 return 你的值到一个变量你必须使用 Promise 如下。

    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

我明白了。不知道这是否是最好的方法,但它确实有效。

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);
          }
      })
   })
}