我在 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();
}
但是当我运行它时,控制台日志显示“Entering function”,然后是“Entering Promise”,然后执行转到 SetId
而没有调用 adminGetUser< 中指定的回调
.
如果我让调试器在主流程完成后继续,最终我会从回调函数中获取日志,所以它最终会运行。
为什么 Promise 在没有调用 resolve
的情况下跳到 then?
最佳答案
.then
接受一个函数 作为参数。当你做的时候
PromiseConfirmIdNotSet(userId)
.then(SetId(userId, identityId))
.catch();
PromiseConfirmIdNotSet
被调用,同步,SetId
被调用,同时解释器尝试构造一个 Promise
从传递给 .then
的函数链。 (但是 SetId
不返回函数)然后,在那之后,PromiseConfirmIdNotSet
的异步代码运行,并且 Promise
解析 - 这是'按照你想要的顺序。
更改它,以便 SetId
仅在 PromiseConfirmIdNotSet
返回的 promise 解决后调用:
PromiseConfirmIdNotSet(userId)
.then(() => SetId(userId, identityId))
.catch();
问题类似why
addEventListener('click', fn());
不起作用 - 您可以将其更改为 , fn);
或 , () => fn());
。
如果您还希望 context.done
仅在成功的 SetId
之后发生,则将 context.done
调用放在 .然后
:
PromiseConfirmIdNotSet(userId)
.then(() => {
SetId(userId, identityId);
context.done(null, 'Hello World'); // SUCCESS with message
});
关于javascript - Promise:然后在 Resolve 之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53233726/