【问题标题】:Use Async / await while assigning value to global const variable在为全局 const 变量赋值时使用 Async / await
【发布时间】:2022-01-24 00:17:27
【问题描述】:

我正在尝试为模块声明和初始化具有全局范围的 const 变量,它需要从 async/await 的结果中获取值。这是我尝试过的代码,变量仍然未定义。我怎样才能重写它,以便我仍然可以使用一个常量并且它保持所需的值:

const puppet = require('puppeteer')
const browser = (async () => { await puppet.launch() })();
const page = (async () => { await browser.newPage() })();

console.log( "browser holds: " + util.inspect(page) );
     // prints out undefined

我需要设置两个单独的页面,它们将在整个应用程序中使用,以加载不同的页面并根据需要进行处理。

现在,我可以通过将变量声明为 'var' 然后在 .then() 中分配值来做到这一点。但我更愿意为这些使用“const”作为最佳实践。

下面的代码可以让我作为 var 执行此操作并在整个应用程序中使用它:

const puppet = require('puppeteer')

async function setupNewPuppetWithKeys(puppetBrowser, puppetPage ){

  let browser = await puppet.launch();
  let page = await browser.newPage();
  page.setViewport({ width: 1280, height: 800 });

  logger.infoLog("initialized values for - " + puppetBrowser + ", " + puppetPage )
  return { [puppetBrowser] : browser , [puppetPage] : page };
}

var browserDev, pageDev;
setupNewPuppetWithKeys("browserDev", "pageDeV").then( (jsonResult) => {

   logger.infoLog("In Then received : " + util.inspect(jsonResult) );
   browserDev = jsonResult.browserDev;
   pageDev = jsonResult.pageDev;
} );

// I declare more browser and page variables here .. but you get the idea with the one I've done above.

【问题讨论】:

    标签: node.js async-await puppeteer


    【解决方案1】:

    For the moment,不支持顶级异步/等待。您可以做的是创建一个可以在顶层调用的“主”异步函数:

    const puppet = require('puppeteer')
    
    async function main() {
      const browser = await puppet.launch();
      const page = await browser.newPage();
    
      console.log( "browser holds: " + util.inspect(page) );
    }
    
    main();
    

    【讨论】:

    • 谢谢@Seblor。欣赏这个例子,但这不适用于我的用例。我的应用程序要大得多,我需要将它保存在全局级别/模块级别,以便我可以将它传递给其他方法。请参阅我所做的编辑可能会提出疑问,因为我已经添加了更多关于我现在作为解决方法的内容。
    • @selbor。感谢您提供有关不支持顶级异步/等待的链接。很高兴知道。我将浏览该链接上的文档。现在,我想我必须使用 var 方法。
    • 我认为您应该将所有代码保留在函数中,并避免使用全局变量。如果你想继续这样工作,你可以使用let 而不是var
    • 我同意您使用“let”而不是“var”的建议。我尝试使用 'let' 而不是 'var' 并且可以在这里做同样的事情。此处全局/模块级别声明的唯一原因是我不必每次访问页面时都重新创建“浏览器”和“页面”。
    【解决方案2】:
    const puppet = require('puppeteer')
    
    async function main(){
    const browser = await puppet.launch();
    const page = await browser.newPage();
    
    console.log( "browser holds: " + util.inspect(page) );
    }
    

    您不需要定义独立的函数,而是将它们全部包装在一个异步函数中(因为 await 只能在异步函数中使用)现在您将获得所需的值。

    【讨论】:

    • 谢谢@Sankhavaram。您是 Seblor 提供了相同的解决方案,但它不适用于我的用例。请参阅我对问题所做的编辑,因为我添加了更多关于为什么要将变量保留在全局级别的详细信息。
    【解决方案3】:

    我在使用 node.js 时遇到了同样的问题,但找不到答案,但后来尝试了这种技术,如果您使用的是 node.js,这可能会有所帮助。

    诀窍是在异步函数内的global 对象上定义只读变量。该函数完成后,其他代码可以在整个应用程序中直接访问具有全局范围的变量。

    这是一个说明该方法的测试脚本。如果有人有更简单的解决方案,我很想知道。

        "use strict";
    
        // Utility function to set a constant value on the global object
        function setGlobalConst(constName, constValue){
            console.log(`      >> setGlobalConst ${constName} `);
            if( typeof global[constName] !== "undefined" )
                throw new Error(`Attempt to redefine global const ${constName}`);
            Object.defineProperty(global, constName, { value: constValue, writable: false });
        };
    
        // This is the setter function for the global const ABC
        // Note this does not need to be async, it returns a promise
        // synchronously
        function setABC () {
           // Check for the global promise to set the value of ABC
            if(typeof global.prmABC === "undefined" ){ 
                console.log("      >> setABC called for the first time")
    
                // Create the promise that will set the value of ABC some
                // time in the future;
                let setterPromise =
                    (
                        async function(){
                            await delay(2000);
                            setGlobalConst("ABC", "[VALUE OF ABC]");
                            console.log("      >> setter: global const ABC has now been set")
                            return ABC;
                            }
                    )()
    
                    // Save this promise in the global setter promise const prmABC
                    setGlobalConst("prmABC", setterPromise );
    
                    // Return the promise, which will resolve when ABC has been set
                    return setterPromise;
    
            };
    
            // As this has previously been called, we just
            // need to return the promise that was previously
            // saved in the global const prmABC.
            console.log("      >> setABC has already been called")
            return prmABC;
            
        };
    
        // Application code - this is async to ensure that
        // it waits for the ABC setter to resolve before accessing
        // the global const ABC.
        async function run( ){
            console.log(`    1. Before setting, global ABC=${global.ABC}`);
    
            console.log("    2. Calling setABC without waiting");
            setABC();
    
            console.log(`    3. Before setter has resolved, global ABC still =${global.ABC}`)
    
            try{
                console.log("    4. Waiting on the original global setter promise.. delay here...:");
                let myABC1 = await prmABC;
                // The value returned by the resolved prmABC is the value of global const ABC
                console.log(`       4a. >> Resolved value of global prmABC=${myABC1}`); 
                // Also, now that the setter promise is fulfilled, the global const ABC is set
                console.log(`       4b. >> Global const ABC=${ABC}`); 
    
                console.log("    5. We can also get the value of ABC by waiting on a call to setABC()");
                let myABC2 = await setABC();
    
                console.log(`       5a. >> Value returned from resolved setABC() is ${myABC2}`);
    
                console.log(`    7. Accessing value of ABC directly: ABC=${ABC}`);
    
            } catch(e) {
                console.log(`    ERROR: ${e.message}`)
            };
    
            console.log("    8. Calling setABC() again, after it has finished, without waiting");
            setABC();
            
            console.log(`    9. Accessing value of global const ABC again: ABC=${ABC}`);
    
            try{
                console.log("    10. Attempting to change value of ABC directly")
                ABC = "New value of ABC";
            } catch(e) {
                console.log(`    ERROR: ${e.message}`)
            };
    
            console.log("    Run finished---------------------------------");
        };
    
        run();
    
        // Small utility function to provide async promise
        function delay(ms) { 
            return new Promise(resolve => setTimeout(resolve, ms)); 
        } 
    

    此代码的控制台输出为:

    test> node testConstWithAsync
    1. Before setting, global ABC=undefined
    2. Calling setABC without waiting
      >> setABC called for the first time
      >> setGlobalConst prmABC
    3. Before setter has resolved, global ABC still =undefined
    4. Waiting on the original global setter promise.. delay here...:
      >> setGlobalConst ABC
      >> setter: global const ABC has now been set
       4a. >> Resolved value of global prmABC=[VALUE OF ABC]
       4b. >> Global const ABC=[VALUE OF ABC]
    5. We can also get the value of ABC by waiting on a call to setABC()
      >> setABC has already been called
       5a. >> Value returned from resolved setABC() is [VALUE OF ABC]
    7. Accessing value of ABC directly: ABC=[VALUE OF ABC]
    8. Calling setABC() again, after it has finished, without waiting
      >> setABC has already been called
    9. Accessing value of global const ABC again: ABC=[VALUE OF ABC]
    10. Attempting to change value of ABC directly
    ERROR: Cannot assign to read only property 'ABC' of object '#<Object>'
    Run finished---------------------------------
    

    【讨论】:

      猜你喜欢
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多