NodeJ:如何跨多个文件使用Promise?

时间:2019-03-21 17:10:15

标签: javascript node.js

我最初有一个可以保证很好工作的文件,但是后来我意识到我将大量重复使用这些功能,因此决定创建一个新文件来保存该功能并使用module.export,这样我可以在任何地方访问它。如果我在新文件(GlobalResource.js)中console.logcrop_inventory,我得到的是1000,这是正确的,但是当我尝试访问原始文件中的数据时,我得到的是0。

homeController.js

var ResourceGlobal = require('../global/globalResources/ResourcesGlobal');

app.get('/game/:gameid/home', function(req,res){
    if(global.gameId == req.params.gameid){
        setResourceInventory().then(function(){
            console.log(ResourceGlobal.crop_inventory)//I get 0, here even though it should be 1000
            res.render('GameEngine/home/gameHome');
        });
    } else{
        res.send(500, "Not authorized to view this page.");
    }
});


function setResourceInventory(){
    return new Promise(function(resolve,reject){
        Promise.all([ResourceGlobal.getCrop(), ResourceGlobal.getLumber(), ResourceGlobal.getOre(), ResourceGlobal.getOil()]).then(function(){
            resolve();
        });
    });
}

ResourceGlobal.js

var db = require('../../../../db');


module.exports = {

//Resources
crop_inventory: 0,
lumber_inventory: 0,
ore_inventory: 0,
oil_inventory: 0,

//Function gets crop inventory and sets global variable
getCrop: function(){
    return new Promise(function(resolve,reject){
        let sql = "SELECT Crop_Inventory FROM resources WHERE resources_FK_PlayerId = (?) AND resources_FK_GameId = (?)";
        var value = [global.id, global.gameId];
        db.query(sql, value, function(err,result,fields){
            if(err){
                console.log(err);
            } else{
                crop_inventory = result[0].Crop_Inventory;
                console.log(crop_inventory) //I get 1000 which is correct
                resolve();
            }
        });
    })
}

}

// 3还有更多功能适用于木材,矿石和石油

2 个答案:

答案 0 :(得分:0)

resolve()中,您需要传递要解析的值。另外,如果发生错误,您应该reject做出承诺。因此,在您的情况下,getCrop()应该是:

getCrop: function(){
    return new Promise(function(resolve,reject){
        let sql = "SELECT Crop_Inventory FROM resources WHERE resources_FK_PlayerId = (?) AND resources_FK_GameId = (?)";
        var value = [global.id, global.gameId];
        db.query(sql, value, function(err,result,fields){
            if(err){
                console.log(err);
                reject(err);
            } else{
                crop_inventory = result[0].Crop_Inventory;
                console.log(crop_inventory) //I get 1000 which is correct
                resolve(crop_inventory);
            }
        });
    })
}

现在Promise.all()将在其中所有的诺言都得到解决后得到解决。并解析为一个数组,其中包含以相同顺序排列的每个promise的解析值。因此,setResourceInventory()应该是:

function setResourceInventory(){
    return new Promise(function(resolve,reject){
        Promise.all([ResourceGlobal.getCrop(), ResourceGlobal.getLumber(), ResourceGlobal.getOre(), ResourceGlobal.getOil()]).then(function(data){
            resolve(data);
        });
    });
}

因此,您现在可以按以下方式访问数据:

setResourceInventory().then(function(data){
    console.log(data[0]); //getCrop value
    console.log(data[1]); //getLumber value
    res.render('GameEngine/home/gameHome');
});

答案 1 :(得分:0)

为简化参考,您的setResourceInventory()函数可以简化:

function setResourceInventory(){
        return Promise.all([ResourceGlobal.getCrop(), ResourceGlobal.getLumber(), ResourceGlobal.getOre(), ResourceGlobal.getOil()])
}

Promise.all()返回一个可以实现的承诺。