2017-10-28 9 views
0

CoinMarketCap.com ticker API에 연결하는 간단한 바닐라 JS 스크립트입니다.Xhr : API Cryptocurrency 가격 알림 스크립트가 잘못된 값을 반환합니다.

그것이 무엇을해야 :

1)

3)이 경우, (객체

2)의 시간 (X)의 양을 기다리는 3 분 보관 코인 데이터를 검색) 1) 반복 최근 데이터

4를 검색하는) 최근의 데이터와 이전 데이터

5) 만약 비교 동전의 값은 console.log 경고

6) 과정

를 반복까지 간이란 것은 수행합니다 두 객체 (firstValuesecondValue가) 중복입니다. 또한 다시 시작할 때 (main() 함수를 다시 호출하면)이 두 개체의 내용이 올라가고 이전 값이 표시되지 않습니다.

// Variables 

// Set first recorded value 
var firstValue; 

// Set second value (most recent) 
var secondValue; 


// Get the obj from CoinMarketCap API 
function getCoinValues() { 
    var requestURL ="https://api.coinmarketcap.com/v1/ticker/?limit=10"; 
    var request = new XMLHttpRequest(); 
    request.open("GET", requestURL); 
    request.send(); 

    // When loaded assign to obj variable and return it 
    request.onload = function getUsdValues() { 
     // Save data to the 'obj' object 
     obj = JSON.parse(request.response); 
     console.log("Retrieved coin data"); 
     }; 
    return obj; 
} 


// Wait 
function wait(ms){ 
    console.log("Waiting.") 
    var start = new Date().getTime(); 
    var end = start; 
    while(end < start + ms) { 
    end = new Date().getTime(); 
    }   
} 


// Compare two objects 
function comparePrices (obj1, obj2) { 
    // Take price from one array, compare to the other 
    for (var i = 0; i < obj1.length; i++) { 
      // console.log(JSON.stringify(obj2[i].id) + " OLD:" + obj1[i].price_usd + "NEW:" + obj2[i].price_usd) 
      if (obj2[i].price_usd > obj1[i].price_usd) { 
       console.log(JSON.stringify(obj2[i].id) + " has increased!"); 
       console.log("From $" + obj1[i].price_usd + " to $" + obj2[i].price_usd); 

      } 
     } 

} 


// Main function // 

function main() { 
    // Get 1st coin values 
    console.log("Getting first values"); 
    firstValue = getCoinValues(); 

    // Wait 
    console.log("Waiting") 
    wait(30000); 

    // Retrieve new values 
    console.log("Getting second values") 
    secondValue = getCoinValues(); 

    // Compare two sets of values 
    console.log("About to compare prices") 
    comparePrices(firstValue, secondValue); 
    console.log("Prices compared") 

    // Do it all again 

    // "Emptying" the variables 
    firstValue = null 
    secondValue = null 

    // Starting the main loop 
    main(); 

} 

main(); 

은 왜 firstValuesecondValue 표시 다른 결과는 가격 효과적으로 시세에 다양 한 않는 경우에도?

기술적 전문 용어의 부적절한 사용과 전반적인 코딩 초보자를 용서하십시오.

답변

1

OP 코드에는 기술적 및 논리적 오류가 많이 포함되어 있습니다. 고정 코드 내부의 주석을 참조하십시오.

// Variables 

// Set first recorded value 
//var firstValue; //no use 

// Set second value (most recent) 
//var secondValue; //no use 

//Save AJAX response here 
var currentValue = []; 
//define the const URL 
var requestURL = "https://api.coinmarketcap.com/v1/ticker/?limit=10"; 

// Get the obj from CoinMarketCap API - wrong description 
//Process request to API 
function getCoinValues() { 
    //var requestURL = "https://api.coinmarketcap.com/v1/ticker/?limit=10"; 
    var request = new XMLHttpRequest(); 
    request.open("GET", requestURL); 
    //request.send();//dedine a handler first 
    request.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { //**this** is request 
      var tmpObj = JSON.parse(this.responseText); 
      if (currentValue && tmpObj) {//compare when both arrays exist 
       comparePrices(currentValue, tmpObj); 
      } 
      if (tmpObj) //response received and parsed 
       currentValue = tmpObj; 
      //console.log(tmpObj); 
     } 
    } 
    //now it is good time to send request 
    request.send(); 

    // When loaded assign to obj variable and return it 
    //request.onload = function getUsdValues() { 
    // // Save data to the 'obj' object 
    // obj = JSON.parse(request.response); //obj was never defined 
    // console.log("Retrieved coin data"); 
    //}; 
    //return obj; //never try to return anything from asynchronous function 
} 


// Wait 
//Good to hang the system 
/* 
function wait(ms) { 
    console.log("Waiting.") 
    var start = new Date().getTime(); 
    var end = start; 
    while (end < start + ms) { 
     end = new Date().getTime(); 
    } 
} 
*/ 

// Compare two objects (arrays in fact) 
function comparePrices(obj1, obj2) { //usage: comparePrices(current,new) 
    console.log(new Date().toLocaleTimeString()); 
    // Take price from one array, compare to the other 
    for (var i = 0; i < obj1.length; i++) { 
     // console.log(JSON.stringify(obj2[i].id) + " OLD:" + obj1[i].price_usd + "NEW:" + obj2[i].price_usd) 
     if (obj2[i].price_usd > obj1[i].price_usd) { 
      //console.log(JSON.stringify(obj2[i].id) + " has increased!"); //no need to stringify. 
      console.log(obj2[i].id + " has increased! From $" + obj1[i].price_usd + " to $" + obj2[i].price_usd); 
     } else if (obj2[i].price_usd < obj1[i].price_usd) { 
      console.log(obj2[i].id + " has decreased! From $" + obj1[i].price_usd + " to $" + obj2[i].price_usd); 
     } else { 
      console.log(obj2[i].id + " No change $" + obj2[i].price_usd); 
     } 
    } 
} 

// Main function // 

function main() { 
    getCoinValues(); 
    setTimeout(main, 30000);//run again in 30 sec 
    return; 
    //All remaining code is wrong 

    //// Get 1st coin values 
    //console.log("Getting first values"); 
    //firstValue = getCoinValues(); 

    //// Wait 
    //console.log("Waiting") 
    //wait(30000); 

    //// Retrieve new values 
    //console.log("Getting second values") 
    //secondValue = getCoinValues(); 

    //// Compare two sets of values 
    //console.log("About to compare prices") 
    //comparePrices(firstValue, secondValue); 
    //console.log("Prices compared") 

    //// Do it all again 

    //// "Emptying" the variables 
    //firstValue = null 
    //secondValue = null 

    //// Starting the main loop 
    //main(); 

} 

main(); 

나는 코드 스 니펫을 만들려고했으나하지 않기로 결정했습니다.

+0

대단합니다! 철저히 감사드립니다, @Alex! 내 (수많은) 실수를 모두 알아 내려고 노력하겠다. – user2331291

+0

수락 함 도와 줘서 고마워. – user2331291