我在使用 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---------------------------------