【发布时间】:2019-04-13 11:53:30
【问题描述】:
我在 Node.js 中做过的第一件事是,我正在编写一个 AWS Lambda 函数,并且我想在执行其他任何操作之前检查用户的自定义属性是否具有值。因为我被告知 Promises 是同步处理异步方法的方式,所以我编写了函数:
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var cogId = new AWS.CognitoIdentityServiceProvider();
exports.handler = function (event, context) {
if (event != null)
{
var identityId = context.identity.cognitoIdentityId;
if (event.userId != null)
{
var userId = event.userId;
PromiseConfirmIdNotSet(userId)
.then(SetId(userId, identityId))
.catch();
}
}
context.done(null, 'Hello World'); // SUCCESS with message
};
function PromiseConfirmIdNotSet(userId)
{
console.log('Entering function');
return new Promise(function (resolve, reject) {
console.log('Entering Promise');
cogId.adminGetUser({
UserPoolId: myUserPool,
UserId: userId
},
function (err, data) {
console.log('err = ' + JSON.stringify(err));
console.log('data = ' + JSON.stringify(err));
if (data != null && data.UserAttributes.Name == null) {
console.log('Calling resolve');
resolve();
} else {
console.log('Calling reject');
reject();
}
});
});
console.log('Exiting Promise');
}
function SetId(userId, identityId)
{
cogId.updateUserAttributes();
}
但是当我运行它时,控制台日志显示“输入函数”,然后显示“输入承诺”,然后执行转到SetId,而没有调用adminGetUser中指定的回调。
如果我在主流程完成后让调试器继续运行,最终我会从回调函数中获取日志,所以它最终会运行。
为什么 Promise 跳到 then 却没有 resolve 被调用?
【问题讨论】:
-
您能否将您获得的日志输出与您期望的日志输出包括在内?此外,新的 ECMA 规范为您可能想要研究的异步函数(在 AWS Lambda for Node.js 8.10 中支持)提供了新语法,因为它使代码更简洁:
async/await:@987654321 @
标签: javascript node.js promise aws-lambda