简体   繁体   English

Javascript Cognito了解异步并等待?

[英]Javascript Cognito understanding async and await?

I'm calling this function to retrieve a user attribute, however when i'm testing the function the return result is always "test" and then it goes through "cognitoUser.getUserAttributes" and logs the actual result. 我正在调用此函数来检索用户属性,但是当我测试函数时,返回结果始终为“test”,然后它将通过“cognitoUser.getUserAttributes”并记录实际结果。 I'm not sure why but "cognitoUser.getUserAttributes" seems to be skipped initially. 我不确定为什么但是“cognitoUser.getUserAttributes”似乎最初被跳过了。

when run, it prints out test and instead of the actual result 在运行时,它打印出测试而不是实际结果

any ideas? 有任何想法吗?

function retrieveattribute(e) {
  var ans = "test";
  var e = "custom:InstanceID_1";
  cognitoUser.getUserAttributes(function(err, result) {
    if (err) {
      alert(err);
      return;
    }
    for (i = 0; i < result.length; i++) {
      if (result[i].getName() == e) {
        ans = result[i].getValue();
        console.log(ans);
        return ans;
      }
    }
  });
  return ans;
}

For start "async code" you need wrap you function to promise: 要启动“异步代码”,您需要将函数包装为承诺:

function retrieveattribute(e) {
    return new Promise(function(res) {
        var ans = "test";
        var e = "custom:InstanceID_1";

        cognitoUser.getUserAttributes(function(err, result) {
            if (err) {
                alert(err);
                return;
            }
            for (i = 0; i < result.length; i++) {
                if (result[i].getName() == e) {
                    ans = result[i].getValue();
                    console.log(ans);
                    res(ans);
                }
            }
        });
    })
}

After it you can use as promise: 在它之后你可以使用承诺:

   retrieveattribute(e).then(t => console.log(t))

Or await it at async function: 或等待它在异步功能:

   await retrieveattribute(e)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM