我有一个用户模型:
export class User extends Serializable{
id: string;
first_name: string;
middle_name: string;
last_name: string;
email: string;
image_url: string;
// mykeyStore
static store:StoreDatabase = new StoreDatabase("mykeyStore");
... More code...
还有一个 loadProfile()
函数返回一个 promise。
loadProfile():Dexie.Promise<any>{
let promise = User.store.get('user')
.then(
tuple => {
// Extract User Data from tuple
let user_data = tuple && tuple.value
// Fill User attribute for Tuple's value
for (var attr in user_data) {
this[attr] = user_data[attr];
}
});
return promise;
}
我如何构造我的代码,以便调用 loadProfile
不会总是运行 then
,如果它已经解析,通过调用以下方法:
let user = new User();
user.loadProfile().then( () =>
console.log(user.first_name)
);
最佳答案
在您的情况下,loadProfile
将再次执行内部代码。为避免这种情况,您需要将 promise 存储在某个变量中。例如(es6,因为我不太了解 typescript ):
// Execute code inside loadProfile and store the promise in some variable
const loadProfilePromise = user.loadProfile();
// Will show Hurray
loadProfilePromise.then(() => console.log('Hurray');
// Will not execute code inside loadProfile again, but will show 'Hurray2'
setTimeout(() => {
loadProfilePromise.then(() => {
console.log('Hurray2'));
});
}, 100);
此外,不要忘记处理 promise 中的异常和拒绝,并记录它们;D
关于javascript - 如何让 Promise 在已经解决时不重新运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39013740/