I'm trying to wrap my brain around promises and I'm refactoring some nested callbacks into promises. I'm encountering something I don't understand and any help anyone could provide would be appreciated. There's definitely something wrong with my for-loop; I suppose that sort of structure is invalid but I'm not sure what to do about it. Also, the result coming back from insertTickersDb function appears to take my entire array and insert it as a single record - not what I was hoping for. I know I'm doing things wrong - please help me understand which things.
I have bound a function to mongoose like this:
var insertTickersDb = q.nfbind(db.tickers.insert.bind(db.tickers));
I have an insert function that looks like this:
function insertTickers(symbols) {
console.log("inserting tickers");
if (symbols) {
if (!(symbols instanceof Array)) {
symbols = [symbols];
}
var tickersToInsert = [];
symbols.map(function(symbol) {
tickersToInsert.push({
symbol: symbol
});
});
console.log("tickersToInsert = " + JSON.stringify(tickersToInsert));
return insertTickersDb(tickersToInsert);
}
}
and I have a test like this:
describe("tickerIntegrationTests internal testing tools", function() {
it("insertTickers should insert the provided tickers", function(done) {
var tickerList = ["A", "B", "C"];
insertTickers(tickerList).then(function(data) {
console.log("inside insertTickers, data = " + JSON.stringify(data));
for (var d = 0; d < data.length; d++) {
console.log("d = " + d + ",data[d].symbol = " + data[d].symbol);
assert.equal(data[d].symbol, tickerList[d]);
}
}).then(removeTickers(tickerList)).done(function(){done();});
});
});
My output is:
tickerIntegrationTests internal testing tools
inserting tickers
tickersToInsert = [{"symbol":"A"},{"symbol":"B"},{"symbol":"C"}]
inside insertTickers, data = [[{"symbol":"A","_id":"552faf5c0aac9578428320da"},{"symbol":"B","_id":"552faf5c0aac9578428320db"},{"symbol":"C","_id":"552faf5c0aac9578428320dc"}],{"n":0}]
d = 0,data[d].symbol = undefined
It might help if you expand out the json of the inner call
[
[
{
"symbol": "A",
"_id": "552faf5c0aac9578428320da"
},
{
"symbol": "B",
"_id": "552faf5c0aac9578428320db"
},
{
"symbol": "C",
"_id": "552faf5c0aac9578428320dc"
}
],
{
"n": 0
}
]
Now you can see the the data is an array whose first element is the data array you are expecting. If you looked at data[0]
you would find the first ticker. d[0].symbol
should contain what you are looking for. You might want to look at t