【问题标题】:Wait for async function to end等待异步函数结束
【发布时间】:2021-10-07 14:51:12
【问题描述】:

我有以下函数可以正常工作,除了我需要等到它完成执行下一条语句:

zohoAuth.zoho_oAuth = function () {
    // return new Promise((resolve, reject) => {

        zohoAuth.state = utils.uuid();

        const url = zohoAuth.authorizationURL();

        zohoAuth.popUp(url);
        getAuthCodeFromCatalyst();
        //setTimeout(getAuthCodeFromCatalyst,1000);
        function getAuthCodeFromCatalyst() {
            return new Promise(function (resolve, reject) {
                (async function waitForFoo() {
                    const gotAuthState = await zohoAuth.getUserDataFromStorageState(zohoAuth.state)
                    await gotAuthState;
                    if (gotAuthState) return resolve();
                    setTimeout(waitForFoo, 1000);
                })();
            });
        }


        console.log("bottom of zoho auth")
        return true;
    // });
}

我用这个来调用函数:

zohoAuth.zoho_oAuth();
console.log("done waiting");

我如何等待这个完成?

【问题讨论】:

  • 等待它?使用.then?另外,为什么你有一个常规函数,它返回一个包装异步 IIFE 的新 Promise,而不是仅仅编写一个异步函数?
  • 另外,等待getUserDataFromStorageState 然后等待结果看起来很奇怪。你确定你正确使用了这个工具吗?
  • 上述功能适用于我想要它做的事情。我正在等待用户按 OK,然后从数据库中读取结果。所以我每秒都在调用“getUserDataFromStorageState”。该功能的作用。我只需要等到我从数据库中得到答案

标签: javascript async-await


【解决方案1】:

你让自己变得更难了。确保避免explicit promise constructor anti-pattern -

zohoAuth.zoho_oAuth = function () {
  zohoAuth.state = utils.uuid();
  const url = zohoAuth.authorizationURL();
  zohoAuth.popUp(url);
  return zohoAuth.getUserDataFromStorageState(zohoAuth.state);
}

您可以通过将.then 处理程序附加到函数调用的结果来访问结果 -

zohoAuth.zoho_oAuth()
  .then(authState => console.log("bottom of auth state", authState))
  .catch(console.error)

如果您想使用asyncawait,请继续。如果发生错误,不要捕获它。而是让它冒泡并由调用者处理 -

async function doAuth (...) {
  const authState = await zohoAuth.zoho_oAuth()
  console.log("received auth state", authState)
  return "done" // or whatever
})

doAuth().then(console.log, console.error)

【讨论】:

    【解决方案2】:

    您应该在承诺上考虑awaiting。下面 sn -p 显示了使用await的区别-

    const asyncFunction = function() {
      return new Promise(function(resolve, reject) {
        setTimeout(() => {
          console.log('inside promise');
          resolve();
        }, 100);
      });
    }
    
    function callWithoutAwait() {
      asyncFunction();
      console.log('after without await function');
    }
    
    callWithoutAwait();
    
    async function callWithAwait() {
      await asyncFunction();
      console.log('after with await function');
    }
    
    callWithAwait();

    【讨论】:

    • @Jamiec,它展示了如何等待承诺。
    • @Jamiec,我已经编辑了 sn-p,所以它更有意义。
    【解决方案3】:

    我能够完成下面我需要的代码。感谢您的帮助!

    zohoAuth.zoho_oAuth = function() {
        zohoAuth.state = utils.uuid();
        const url = zohoAuth.authorizationURL();
        zohoAuth.popUp(url);
        
        return new Promise(function (resolve, reject) {
            (async function waitForFoo() {
                const gotAuthState = await zohoAuth.getUserDataFromStorageState(zohoAuth.state)
                await gotAuthState;
                if (gotAuthState) return resolve();
                setTimeout(waitForFoo, 1000);
            })();
        });
    }
    

    这就是电话:

    zohoAuth.zoho_oAuth()
      .then(authState => console.log("bottom of auth state", authState))
      .catch(console.error)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2023-04-08
      相关资源
      最近更新 更多