gpt4 book ai didi

javascript - 由于获取结果未定义而获得响应时出现问题

转载 作者:行者123 更新时间:2023-12-02 23:01:52 25 4
gpt4 key购买 nike

我在从一个 Controller 向另一 Controller 获取响应时遇到问题。

我尝试将响应从“ClientRegisterController.js”返回到“UserController.js”,但得到的结果为“未定义”。

请参阅以下代码以供引用。

ClientRegisterController.js

async RegisterUser(Username, roleid, callback) {
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'));

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;
}
// console.log("Username2",Username)

// 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, function (err, client) {
if (err) {

let connError = new Error(500, "Error connecting to DFARM database", err);
response.httpstatus = 500;
response.message = "Error connecting to DFARM database :" + connError;
// res.status(connError.status).json(connError);
return response;
} else {

client.db(config.Database.DFARM.dbName).collection("Role").find(query1).toArray(function (err, docs) {
if (err) {
response.httpstatus = 500;
response.message = "Error with DB :" + err;
return response;
// need to return
} else {
// console.log('Role name DB', docs);
console.log('Role name DB',docs[0].name);
name = docs[0].name;
query1.name = name;

const doStuffAsync = async () => {
setAsyncTimeout(async () => {

const secret = await ca.register({
enrollmentID: Username,
role: 'client',
attrs: [{name: "approle",value: query1.name,ecert: true }]
}, adminIdentity);
console.log('secret', secret); // return secret;

const enrollment = await ca.enroll({
enrollmentID: Username,enrollmentSecret: secret
});
// console.log('enrollment', enrollment);
const userIdentity = X509WalletMixin.createIdentity('DfarmadminMSP', enrollment.certificate, enrollment.key.toBytes());
// console.log("userIdentity", userIdentity)
await wallet.import(Username, userIdentity);
console.log(`Successfully enrolled user ${Username} and imported it into the wallet`);
response.secret = secret;
// return response;
response.data = userIdentity
response.httpstatus = 200;
response.message = `Successfully registered admin user ${Username} and imported it into the wallet`;
console.log('result before', response);// result come here
return callback(response); // response not return properly or not getting properly in "UserController.js"

}, 4000);
}
doStuffAsync();
}
client.close();
})
}
})
} catch (error) {
response.error = error;
response.httpstatus = 500;
response.message = "Failed to enroll admin due to above error";
return response;
}
};

"UserController.js"

   clientregister.RegisterUser(VZID, roleid, next).delay(8000).then((result) => {
console.log("data result", result)// result getting undefined.as not getting res from "ClientRegisterController.js".
})

我花了很多时间来查找结果,但回调和异步/等待等所有内容仍然未定义,因此请有人帮助我找出导致结果未定义的问题。

提前致谢

最佳答案

快速修复:只需为函数提供适当的回调即可。

clientregister.RegisterUser(VZID, roleid, (response) => 
{
console.log(response);
});

但这是一个奇怪的函数。看起来好像有人采用了同步代码并严重地在其上打了异步补丁。您会看到,该函数是async,它的返回值将始终是Promise。无论代码在哪里使用return,返回值都不会去任何地方。代码应该做的是调用 resolve,而不是 return。

此外,超时结构已被破坏。

编辑:实际上,async 函数的返回值确实会去某个地方。它们被隐式地resolved。考虑一下

function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve("resolved");
}, 2000);
});
}

async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
return "RETURN " + result;
}

console.log( asyncCall().then( (r) => { console.log(r) } ) );


> "calling"
> [object Promise]
> "resolved"
> "RETURN resolved"

所以,这不是问题。

关于javascript - 由于获取结果未定义而获得响应时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57748515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com