javascript - 如何让 Promise 在已经解决时不重新运行代码?

标签 javascript typescript promise

我有一个用户模型:

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/

相关文章:

javascript - 如何扩展 material-ui 组件

html - Angular 4 Material - mat-button 样式未应用于 mat-dialog 组件

javascript - 将 <Mutation> 改为 useMutation

node.js - typescript 。不在特定机器上编译

javascript - 交互式 PDF 表单验证 Javascript

javascript - 我有多个 iframe,如何检测第一个加载的

javascript - TypeError : Cannot read property 'center' of undefined (Three. js + React.js)

javascript - Angular : Return id From $http Inside Parent Function

javascript - 如何在从 API 获取数据时添加加载动画? Vanilla js

JavaScript 链式 Promises 意外的解析顺序