在进行异步和等待时得到空响应

时间:2019-08-23 22:30:43

标签: javascript node.js

我是node.js和javascript的新手。我对自己的代码感到困惑,因为它给了我空洞的响应。我正在尝试实现promise和async and await功能,但是却得到响应{}。

有人可以帮助我了解我哪里错了吗

请参见下面的代码,虽然可能会用很长时间,但是我在没有得到空结果的等待问题上需要帮助

var response = {};
var newSecret ='';
class FabricClientRegister {
    constructor() {
        console.log("called constructer");
    }

    async RegisterUser(Username, roleid) {
        try {
            const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
                setTimeout(() => {
                    cb();
                    resolve();
                }, timeout);
            });


            let query1 = {}
            query1.RoleID = roleid;
            //   query1.name = ''; 
            var name ='';
            console.log('roleid',roleid)
            //   console.log('Username',Username);
            var fs = require('fs');
            var obj = JSON.parse(fs.readFileSync('./config/Config.json', 'utf8'));

            // var Username = req.body.username;
            console.log('Username',Username)

            const walletPath = path.join(process.cwd(), 'wallet');
            const wallet = new FileSystemWallet(walletPath);
            console.log(`Wallet path: ${walletPath}`);

            // Check to see if we've already enrolled the user.
            const userExists = await wallet.exists(Username);
            if (userExists) {
                response.data = null;
                response.httpstatus = 400;
                response.message = `An identity for the  ${Username} already exists in the wallet`;
                return response;
            }
            console.log("Username1",Username)
            // Check to see if we've already enrolled the admin user.
            const adminExists = await wallet.exists(appAdmin);
            if (!adminExists) {
                response.data = null;
                response.httpstatus = 400;
                response.message = "Am admin identity is not registered . please register admin first";
                return response;
            }

            // Create a new gateway for connecting to our peer node.
            const gateway = new Gateway();
            await gateway.connect(ccp, { wallet, identity: appAdmin,  discovery: { enabled: false, asLocalhost: true }
                /*** Uncomment lines below to disable commit listener on submit ****/
                , eventHandlerOptions: {
                    strategy: null
                }
            });

            // Get the CA client object from the gateway for interacting with the CA.
            const ca = gateway.getClient().getCertificateAuthority();
            const adminIdentity = gateway.getCurrentIdentity();
            console.log("Username4",Username)

            MongoClient.connect(config.Database.DFARM.connectString, async function (err, client) {
                if (err) {
                    let connError = new Error(500, "Error connecting to DFARM database", err);
                    res.status(connError.status).json(connError);
                }
                else {
                    client.db(config.Database.DFARM.dbName).collection("Role").find(query1).toArray(function (err, docs) {
                        if(err) {
                            console.log('err db',err);
                        } else{
                            console.log('Role name DB',docs);
                            name = docs[0].name;
                            query1.name = name;
                            console.log('Role',query1);
                        }
                        client.close();
                    })
                }
            })

            setTimeout(() => console.log('Role 10',query1.name), 5 * 1000);

            const doStuffAsync = async () => {

            setAsyncTimeout( async () => {
                console.log('Role Name',query1.name);
                const secret =  await ca.register({enrollmentID: Username, role: query1.name}, adminIdentity);
                console.log('secret',secret);
                response.secret = secret;
                newSecret = secret;
                console.log('newSecret', newSecret );

                response.httpstatus = 200;
                response.message = `Successfully registered admin user ${Username} and imported it into the wallet`;
                return response;
                }, 10000);
            };

            doStuffAsync();
        //      .then(function(result) {
        //     //     console.log('promise result',result) // error here undefined
        //      }).catch(err)
        //      {
        //          console.log("eee", err)
        //      };
            console.log('newSecret1', newSecret)
            console.log('respones', response)
            return newSecret;
        } catch (error) {
            response.error = error;
            response.httpstatus = 500;
            response.message = "Failed to enroll admin due to above error";
            return response;
        }
    }
};

请在CLI中查看以下输出

Username Abhinav345
called constructer
roleid 1
Username Abhinav345
Wallet path: /vagrant/Dfarm-app/dFarmUserService/dFarmUserService/wallet
Username1 Abhinav345
Username4 Abhinav345
newSecret1 
respones {} //getting empty one however need some data
data result 
Role name DB [ { _id: 5d029dec7e8409b489e04cff,
    appName: 'Farmer',
    RoleID: 1,
    name: 'farmer',
    routes: [ [Object], [Object], [Object], [Object] ],
    tabs: [ [Object], [Object], [Object], [Object] ] } ]
Role { RoleID: 1, name: 'farmer' }
Role 10 farmer
Role Name farmer
secret XXCephExVetS
newSecret XXCephExVetS

1 个答案:

答案 0 :(得分:0)

也许您应该考虑将await放在doStuffAsync()之前。