解决调用自己的函数的Promise

use*_*352 1 javascript promise es6-promise

如果我调用此函数,它似乎不起作用.它正在做的只是等待全局变量"window.AppApi"在做事之前进行初始化

我觉得也许是因为我在超时时再次调用该功能?是否有一些我缺少使这项工作?如果它不可能是一个好的选择..

initializeApp()
  .then(( result ) => {
    console.log( 'it worked!' );  // does not go here
  });


export const initializeApp = () => {
  return new Promise(( resolve, reject ) => {
    // wait for App API to be initialized
    if ( window.AppApi ) {
      console.log( 'App initialized.' );
      resolve( true );
    }
    else {
      console.log( 'waiting for App to initialize...' );
      setTimeout( () => initializeApp(), 250 );
    }
  });
};
Run Code Online (Sandbox Code Playgroud)

dfs*_*fsq 5

从技术上讲,即使没有使用旧的优秀Object.defineProperty setter进行脏处理,你也可以做到这一点:

const initializeApp = () => {
  return new Promise((resolve, reject) => {
    if (window.AppApi) {
      resolve(true);
      return;
    }

    Object.defineProperty(window, 'AppApi', {
      set (value) {
        console.log('App initialized.');
        resolve(true);
        return value
      }
    })
  });
};

initializeApp()
  .then((result) => {
    console.log('it worked!'); // does not go here
  });

setTimeout(() => {
  window.AppApi = { test: 123 }
}, 2000)
Run Code Online (Sandbox Code Playgroud)