Node.js中数组的异步处理

时间:2016-10-17 16:28:05

标签: javascript arrays node.js asynchronous

我正致力于获取数组中存在的符号数据的功能。请看下面的代码。

我使用for循环遍历数组,但我的代码中的所有计算仅发生在arra的最后一个元素中(请检查代码中的注释)。我不是100%肯定这个问题的原因,但我相信这是因为Node.js的异步处理。

    var symbol = ['symbol1', 'symbol2','symbol3'];
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1;
    var yyyy = today.getFullYear();
    if (dd < 10) {
        dd = '0' + dd
    }
    if (mm < 10) {
        mm = '0' + mm
    }
    var today1 = yyyy + '-' + mm + '-' + dd;

    //for loop start
    for (sname in symbol) {
        sname = symbol[sname].substring(4);
        sname1 = sname.replace("%26", '&');
        History.find({ "symbol": sname1 }, function(err, stock) {
            if (err) {
                next();
            }
            if (stock != '') {
                var objStr = stock[0].values.sort(custom_sort).reverse();
                objStr = JSON.stringify(objStr[0]);
                var jsonObj = JSON.parse(objStr);
                var date = new Date(jsonObj.Date);
                var fromDate = date.date("YYYY-MM-DD");
                console.log(sname + ' and ' + sname1); //It should print symbol1,symbol2.

                // But I am getting symbol3 all the time.
                console.log(fromDate);
                console.log(today1);
                yahooFinance.historical({
                    symbol: sname + '.NS',
                    from: fromDate,
                    to: today1
                }, function(err, quotes) {
                    if (err) {
                        console.log("Error in fetching data");
                    }
                    if (quotes == '') {
                            console.log("No latest records found to insert");
                    }
                    for (var objCounter in quotes) {
                        var insertObj = {
                            'Date': quotes[objCounter].date.date("YYYY-MM-DD"),
                            'Open': quotes[objCounter].open,
                            'Close': quotes[objCounter].close,
                            'High': quotes[objCounter].high,
                            'Low': quotes[objCounter].low,
                            'AdjClose': quotes[objCounter].adjClose,
                            'Volume': quotes[objCounter].volume
                        };
                        History.findOneAndUpdate({ symbol: sname1 }, { $push: { values: insertObj } }, { safe: true, upsert: true },
                            function(err, model) {
                                if (err) {
                                    console.log(err);
                                } else {
                                    console.log("Record inserted for " + sname1)
                                }
                            }
                        );
                    }
                });
            }
            else {
                console.log("Not Found");
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用 bind 来解决问题

只需将History.find()内的回调方法与您要访问的变量绑定即可。绑定后,您可以使用关键字

访问您的变量

以下是示例代码。

var symbol = ['symbol1', 'symbol2', 'symbol3']
var today = new Date()
var dd = today.getDate()
var mm = today.getMonth() + 1
var yyyy = today.getFullYear()
if (dd < 10) {
  dd = '0' + dd
}
if (mm < 10) {
  mm = '0' + mm
}
var today1 = yyyy + '-' + mm + '-' + dd
// for loop start
for (sname in symbol) {
  sname = symbol[sname].substring(4)
  sname1 = sname.replace('%26', '&')
  History.find({ 'symbol': sname1 }, function (err, stock) {

    //access your sname and sname1
    var sname = this[0] 
    var sname1 = this[1]
    if (err) {
      next()
    }
    //your code....

  }.bind([sname,sname1])) //bind whatever variables you want to bind in this keyword with the callback function.
}