首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步等待未按预期返回值

异步等待未按预期返回值
EN

Stack Overflow用户
提问于 2022-01-20 11:27:43
回答 2查看 872关注 0票数 0

我对异步等待有了基本的理解,但我似乎遗漏了一些东西。

请参阅下面的代码。我在整个过程中放置了console.log行来跟踪执行。我希望每个console.log都应该按照顺序返回令牌。但是'Token1‘和'Token3’返回‘未定义’,而'Token2‘返回实际的令牌。

问题:

  • 我正在正确地使用异步等待吗?
  • 我返回了credentials.access_token正确吗?

代码语言:javascript
复制
async function GetAuthTokenAsync() {
  // Initialize the 2-legged OAuth2 client, set specific scopes and optionally set the `autoRefresh` parameter to true
  // if you want the token to auto refresh
  var autoRefresh = true; // or false

  var oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(
    FORGE_CLIENT_ID,
    FORGE_CLIENT_SECRET,
    ["data:read", "data:write"],
    autoRefresh
  );

  oAuth2TwoLegged.authenticate().then(
    function (credentials) {
      // The `credentials` object contains an access_token that is being used to call the endpoints.
      // In addition, this object is applied globally on the oAuth2TwoLegged client that you should use when calling secure endpoints.
      console.log("Token2: ", credentials.access_token);                 //RETURNS THE TOKEN
      return credentials.access_token;
      },
    function (err) {
      console.error(err);
    }
  );
}

async function Token() {
  const token = await GetAuthTokenAsync();
  console.log("Token1: ", token);                                        //RETURNS 'undefined'
  return token;
}

Token().then(AuthToken => console.log('Token3: ', AuthToken));           //RETURNS 'undefined'
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-01-20 11:40:38

你没有很好地使用它。每个异步函数都返回一个Promise,但是如果没有显式返回语句,它将返回一个值为undefined的解析承诺。这就是为什么您将Token1视为undefined的原因。您的GetAuthTokenAsync运行该调用,但它不对结果进行await,也不返回任何内容。

我已经标记了您的代码,以显示需要在下面进行哪些更改。

代码语言:javascript
复制
async function GetAuthTokenAsync() {
  // Initialize the 2-legged OAuth2 client, set specific scopes and optionally set the `autoRefresh` parameter to true
  // if you want the token to auto refresh
  var autoRefresh = true; // or false

  var oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(
    FORGE_CLIENT_ID,
    FORGE_CLIENT_SECRET,
    ["data:read", "data:write"],
    autoRefresh
  );

  return oAuth2TwoLegged.authenticate().then(   // <---- Must return a promise
    function (credentials) {
      // The `credentials` object contains an access_token that is being used to call the endpoints.
      // In addition, this object is applied globally on the oAuth2TwoLegged client that you should use when calling secure endpoints.
      console.log("Token2: ", credentials.access_token);                 //RETURNS THE TOKEN
      return credentials.access_token;
      },
    function (err) {
      console.error(err);
    }
  );
}

async function Token() {
  const token = await GetAuthTokenAsync();
  console.log("Token1: ", token);                                        //RETURNS 'undefined'
  return token;
}

Token().then(AuthToken => console.log('Token3: ', AuthToken));

此外,允许在.then函数中使用async,但这会增加读取难度。它可以简化如下:

代码语言:javascript
复制
async function GetAuthTokenAsync() {
  // Initialize the 2-legged OAuth2 client, set specific scopes and optionally set the `autoRefresh` parameter to true
  // if you want the token to auto refresh
  var autoRefresh = true; // or false

  var oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(
    FORGE_CLIENT_ID,
    FORGE_CLIENT_SECRET,
    ["data:read", "data:write"],
    autoRefresh
  );

  const credentials = await oAuth2TwoLegged.authenticate();
  console.log("Token2: ", credentials.access_token);                 
  //RETURNS THE TOKEN
  return credentials.access_token;
}

如果您真的想捕获& console.log,GetAuthTokenAsync内部的错误,那么您可以添加一个.catch()函数,但是最好通常让错误抛出堆栈。

票数 3
EN

Stack Overflow用户

发布于 2022-01-20 11:34:32

你必须这样做

代码语言:javascript
复制
async function GetAuthTokenAsync() {
    // Initialize the 2-legged OAuth2 client, set specific scopes and optionally set the `autoRefresh` parameter to true
    // if you want the token to auto refresh
    var autoRefresh = true; // or false
  
    var oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(
      FORGE_CLIENT_ID,
      FORGE_CLIENT_SECRET,
      ["data:read", "data:write"],
      autoRefresh
    );
  
    // you need to await the token before you can use it
    const credentials = await oAuth2TwoLegged.authenticate()
    // .then(
    //   function (credentials) {
    //     // The `credentials` object contains an access_token that is being used to call the endpoints.
    //     // In addition, this object is applied globally on the oAuth2TwoLegged client that you should use when calling secure endpoints.
    //     console.log("Token2: ", credentials.access_token);                 //RETURNS THE TOKEN
    //     return credentials.access_token;
    //     },
    //   function (err) {
    //     console.error(err);
    //   }
    // );

    return credentials.access_token;
  }
  
  async function Token() {
    const token = await GetAuthTokenAsync();
    console.log("Token1: ", token);                                        //RETURNS 'undefined'
    return token;
  }
  
  Token().then(AuthToken => console.log('Token3: ', AuthToken)); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70785392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档