首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Xhr: API加密货币价格警报脚本返回错误和重复的值

Xhr: API加密货币价格警报脚本返回错误和重复的值
EN

Stack Overflow用户
提问于 2017-10-28 23:07:12
回答 1查看 303关注 0票数 0

这是一个连接到CoinMarketCap.com代码机API的简单的普通JS脚本。

它应该做什么:

1)检索硬币数据,并将其存储在对象中。

2)等待x时间(在本例中为3分钟)

( 3)重复1),检索更多的最新数据

4)比较近期数据和以往数据。

5)如果硬币的价值上升了,console.log提醒

6)重复这一过程

is is:两个对象(firstValuesecondValue)是重复的。另外,当重新启动(再次调用main()函数)时,这两个对象的内容将失败,并显示前面的值。

代码语言:javascript
复制
// 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不显示不同的结果,即使在价格实际上发生了变化的时候?

请原谅任何技术术语的不当使用以及整体编码的新意。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-29 00:51:46

OP代码包含一些技术和逻辑错误。请参阅固定代码内的评论。

代码语言:javascript
复制
// 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();

我正在考虑创建一个代码片段,但我决定不去做。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46995372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档