nodejs : how to make "sequelize then" to be synchronous?

时间:2016-02-03 04:14:28

标签: nodes

var Tmp_Products = sequelize.define('tmp_products_list',{
    name : Sequelize.STRING,
    is_crawled   : Sequelize.BOOLEAN
},{
    freezeTableName : true
});

function get_tmp_products(){
    var ps = new Array();
    Tmp_Products.findAll({
        attributes : ['name'],
        limit : 10
    }).then(function(products){
        for(var p in products){
            console.log(products[p].name); //comment 1
            ps[p] = products[p].name
        }
    });
    console.log('ps',ps)  //comment 2
    return ps
}

In the place "comment 1",it shows many products,but the place "comment 2", it shows a blank array.

I don't want it to be asynchronous here, I want the function finally return a product list, how should I do ?

1 个答案:

答案 0 :(得分:1)

我无法改变其异步性质。希望这有帮助

var Tmp_Products = sequelize.define('tmp_products_list',{
    name : Sequelize.STRING,
    is_crawled   : Sequelize.BOOLEAN
},{
    freezeTableName : true
});

function get_tmp_products(callback){
    var ps = new Array();
    Tmp_Products.findAll({
        attributes : ['name'],
        limit : 10
    }).then(function(products){
        //add something to check error
        for(var p in products){
            console.log(products[p].name); //comment 1
            ps[p] = products[p].name
        }
        console.log('ps',ps)  //comment 2
        callback(err, ps)
    });
}