Promises inside setInterval

I have setIntervalone that fulfills a promise every second, inside the then function of each promise, I put the output in the MongoDB database (although for some reason it does not work).

I want to close the database connection when everything is done, but I don’t know how to make the connection close only started when all promises are done and everything has finished writing to the database.

Here is my current code:

I have a file client.jsdesigned to send a request to the store using the promise and db.jsdesigned to work with the functionality of the database.

client.js

var id = setInterval(function(){

        if (i == (categories.length-1))
            clearInterval(id);


            var category = categories[i];

            client.itemSearch({  
              searchIndex: SearchIndex,
              categoryID: category.id,
              keywords: currentKeyword
            })
            .then(function(results){

                var title = results[0].Title;
                var cat = category.name;
                var price = results[0].Price

                db.insertProduct(title,cat,price).then(function(){
                    console.log("Added " + title);
                })
            },function(err) {
                console.log("error at " + category.name);
            });
            i+=1;
    }, 1000)

queryStore();

db.js

var mongoose = require("mongoose");

mongoose.connect('mongodb://localhost:27017/catalog');

var schema = new mongoose.Schema({
    title           : String,
    category        : String,
    price           : Number,
}, {collection: "catalog"});

var Product = mongoose.model("Product", schema);

Product.remove({}, function() {
    console.log('Database cleared.') 
});


exports.clearDB = function() {
    Product.remove({});
}

exports.insertProduct = function (Title,Category,Price) {
    var entry = new Product({
        title: Title,
        category: Category,
        price: Price,
    });

    entry.save();
}

exports.closeConn = function() {
    console.log("Closing DB Connection");
    mongoose.connect().close();
}

In addition, since I am completely unfamiliar with JavaScript and Node.js, in general, any recommendations or general tips will be greatly appreciated! :)

+4
1

, 1- , /. , , , , . 1- , .

, promises .

, reduce (. " Kerfuffle" , :

array.reduce(function(promise, item) {
    return promise.then(function() {
        return doSomethingAsync(item);
    });
}, Promise.resolve());

Promise ES6 native Promise , , Bluebird.

doSomethingAsync() , :

categories.reduce(function(promise, category) {
    return promise.then(function() {
        return client.itemSearch({
            'searchIndex': SearchIndex,
            'categoryID': category.id,
            'keywords': currentKeyword
        }).then(function(results) {
            var title = results[0].Title;
            var cat = category.name;
            var price = results[0].Price;
            return db.insertProduct(title, cat, price);
        }).then(function() {
            console.log("Added " + title);
        }).catch(function(err) {
            console.log("error at " + category.name);
        });
    });
}, Promise.resolve());

, / promises.

+4

Source: https://habr.com/ru/post/1624010/


All Articles