gpt4 book ai didi

javascript - javascript中异步延迟初始化的规范安全方法是什么?

转载 作者:行者123 更新时间:2023-12-03 12:19:04 26 4
gpt4 key购买 nike

我的程序中有这种惰性初始化代码:

let user = null;        
let getUser = async () => {
if(!user) {
user = await getUserSomehow();
}
return user;
};

我知道这是不安全的,因为如果我有下一个代码可能会出现竞争情况:
// one place of the program
let u1 = await getUser();
...
// another place of the program running during getUserSomehow() for u1 still hasn't finished
let u2 = await getUser();
getUserSomehow()将被调用两次而不是一次。

如何避免这种情况?

最佳答案

第一次调用时,改为分配一个 Promise,在进一步调用时,返回该 Promise:

let userProm = null;
let getUser = () => {
if (!userProm) {
userProm = getUserSomehow();
}
return userProm;
};

更好的是,范围 userProm仅在 getUser 内,更安全和清晰:
const getUser = (() => {
let userProm = null;
return () => {
if (!userProm) {
userProm = getUserSomehow();
}
return userProm;
};
})();

const getUserSomehow = () => {
console.log('getting user');
return Promise.resolve('data');
};

const getUser = (() => {
let userProm = null;
return () => {
if (!userProm) {
userProm = getUserSomehow();
}
return userProm;
};
})();

(async () => {
const userProm1 = getUser();
const userProm2 = getUser();
Promise.all([userProm1, userProm2]).then(() => {
console.log('All done');
});
})();


您现有的代码恰好是安全的,因为分配给 user将在第一次调用 getUser 之前发生完成:

const getUserSomehow = () => {
console.log('Getting user');
return Promise.resolve('data');
};

let user = null;
let getUser = async() => {
if (!user) {
user = await getUserSomehow();
}
return user;
};

(async () => {
let u1 = await getUser();
let u2 = await getUser();
console.log('Done');
})();


但是,如果 Promise 是并行初始化的,则不会是在其中一个为 await 之前。首先完成:

const getUserSomehow = () => {
console.log('Getting user');
return Promise.resolve('data');
};

let user = null;
let getUser = async() => {
if (!user) {
user = await getUserSomehow();
}
return user;
};

(async() => {
let u1Prom = getUser();
let u2Prom = getUser();
await Promise.all([u1Prom, u2Prom]);
console.log('Done');
})();


如上所示,将 Promise 分配给持久变量(而不是 await 中的值 getUser )可以解决此问题。

关于javascript - javascript中异步延迟初始化的规范安全方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58796320/

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