[英]Why is my promise not resolving correctly?
exports.addUser = async(req, res) => {
const {
username,
email,
password
} = req.body;
//hash password
const password_hash = await hashPassword(password);
//check whitelist
this.checkWhitelist(email).then(function(response) {
if (response) {
console.log("RESOLVED TRUE")
//POST user to Airtable
new Promise(function(resolve, reject) {
return usersTable.create({
email,
username,
password_hash,
"email_verified": "false"
},
function(err) {
if (err) {
resolve(false);
console.error(err);
res.send({
"Success": false,
"responseCode": 502,
})
}
resolve(true);
res.send({
"Success": true,
"responseCode": 200,
});
}
).then(function(response) {
if (response) {
const EMAIL_SECRET = "xxxxxxxxxxx";
jwt.sign({
'username': username,
},
EMAIL_SECRET, {
expiresIn: '1d',
},
(err, emailToken) => {
const url = `http://localhost:3000/confirmation/${emailToken}`;
transporter.sendMail({
to: args.email,
subject: 'Confirm Email',
html: `Please click this email to confirm your email: <a href="${url}">${url}</a>`,
});
}
)
}
})
})
} else {
console.log('RESOLVED FALSE')
res.send({
"Success": false,
"responseCode": 403
})
}
})
}
由於某種原因,我在 usersTable.create 創建的usersTable.create
無法正確解析。 當我之后調用.then()
時,出現錯誤: UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'then' of undefined。
就上下文而言,這是一個 webapp 的用戶注冊流程。 首先,對通行證進行哈希處理,然后根據白名單檢查 email(到目前為止,此邏輯有效)。 現在我只需要驗證 email,但無法正確調用 .then .then()
。
這是怎么回事?
在您return createTable
的第一個then
中,您需要return new Promise
以便它可以鏈接到下一個then
。
如果createTable
返回 promise,您可以簡單地編寫return createTable
並去掉包裝它的new Promise
。
由於您在代碼的前面使用了async-await
,因此我建議您完全改用它,因為它使代碼更易於閱讀。
對此,我進行了一次嘗試,
exports.addUser = async(req, res) => {
const {
username,
email,
password
} = req.body;
//hash password
const password_hash = await hashPassword(password);
//check whitelist
try {
const whitelist = await this.checkWhiteList(email)
if (whitelist) {
await usersTable.create() // shortened for readability sake.
const EMAIL_SECRET = 'xxxxxxxxxxx';
jwt.sign(
{
'username': username,
},
EMAIL_SECRET,
{
expiresIn: '1d',
},
(err, emailToken) => {
const url = `http://localhost:3000/confirmation/${emailToken}`;
transporter.sendMail({
to: args.email,
subject: 'Confirm Email',
html: `Please click this email to confirm your email: <a href="${url}">${url}</a>`,
});
}
);
}
res.send({
'Success': true,
'responseCode': 200,
});
} catch (error) {
res.send({
'Success': false,
'responseCode': 403,
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.