我对异步/等待还很陌生,尽管以下代码似乎可以正常工作,但我认为必须有一种更为优雅/最佳实践的方式来编写此功能:
/**
*
* @param {string} email user email address
* @description validates project exists and project owner is userId.
* @returns {Promise} resolves userId if found otherwise null
*/
async getUserFirstAndLastName (userId) {
var userName;
return new Promise(function(resolve, reject){
var params = {
UserPoolId: process.env.userPoolId, /* required */
AttributesToGet: [
'given_name',
'family_name'
/* more items */
],
Filter: `sub = \"${userId}\"`
};
console.log("UserUtils DDB Get User First and Last Name:" + JSON.stringify(params, null,' '));
cognitoidentityserviceprovider.listUsers(params, function(err, data) {
if(err){ // an error occurred
console.log(err, err.stack);
reject(err); // throw error
}
else { // successful response
console.log("Data: " + JSON.stringify(data, null,' '));
if(data.Users.length){
userName = data.Users[0].Attributes[0].Value + " "; // First Name
userName += data.Users[0].Attributes[1].Value; // Last Name
resolve(userName); //return
}
else {
resolve(null); // no user found that matches email
}
}
});
});
}
寻求指导...
答案 0 :(得分:3)
您的代码问题确实似乎在以下方面:
cognitoidentityserviceprovider.listUsers(params, function(err, data) {
...
});
这是旧的callback style way of handling asynchronous code。
您想要编写代码的真正方法是使listUsers
函数接受回调,而不是返回一个promise。然后,您可以通过以下方式编写代码:
async getUserFirstAndLastName (userId) {
const params = {
UserPoolId: process.env.userPoolId, /* required */
AttributesToGet: [
'given_name',
'family_name'
/* more items */
],
Filter: `sub = \"${userId}\"`
};
try {
const data = await cognitoidentityserviceprovider.listUsers(params);
if(data.Users.length){
let userName = data.Users[0].Attributes[0].Value + " "; // First Name
userName += data.Users[0].Attributes[1].Value; // Last Name
return userName;
}
else {
return null; // no user found that matches email
}
}catch(err) {
throw err;
});
});
}
假设您不能直接重写该listUsers
函数,则可以编写一个将其转换为可返回承诺的函数的函数,如下所示:
function convertCallbackFnToAsyncFn(fn) {
//Note that we are returning a function
return (...args) => new Promise(function(resolve, reject){
fn(...args, (err, data) => {
if (err) {
reject(err);
}
else {
resolve(data);
}
});
});
}
并将其与上述解决方案配合使用:
try {
//I'm just naming it newFunction here to be really clear about what we're doing
const newFunction = convertCallbackFnToAsyncFn(cognitoidentityserviceprovider.listUsers);
const data = await newFunction(params);
....
请注意,我在答案中使用了一些ES6扩展/休息和粗箭头语法。