gpt4 book ai didi

node.js - 在为全局 const 变量赋值时使用 Async/await

转载 作者:行者123 更新时间:2023-12-05 06:19:16 30 4
gpt4 key购买 nike

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

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 上遇到了同样的问题,找不到答案,但后来尝试了这种技术,如果您使用的是 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---------------------------------

关于node.js - 在为全局 const 变量赋值时使用 Async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60863519/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com