javascript,在 chrome 网络应用程序中创建 window,如何包含成功调用新 window 函数的承诺?

javascript, create window in chrome web app, how to include a promise for successfully calling a function of the new window?

我想创建一个 window 并且在创建时,运行 一个已经预加载的函数。我必须等到创建 window ,否则该功能不可用且失败。我会说我可以做到这一点。

怎么做?这是我尝试执行的代码

one().then(function() {
  new_panel.contentWindow.load_content(something);
})

function one() {
  var promise = chrome.app.window.create('empty.html', 
  {
    id: 'protein_panel',
    outerBounds: {
      width: 300,
      height: 800,
    },
  },
  function(createdWindow) {
    createdWindow.contentWindow.load_content = function(data) {
      createdWindow.contentWindow.document.getElementById('loading_content').appendChild(data);
    }
    new_panel = createdWindow;
  });

  return promise;
}

它抱怨 one() 函数的 then: Uncaught TypeError: Cannot read 属性 'then' of undefined

更新:稍微修改了代码,仍然不起作用,我使用了 angular 的承诺,因为我正在使用它

one().then(function() {
  new_panel.contentWindow.load_content(something);
})

function one() {
  return chrome.app.window.create('empty.html', 
  {
    id: 'protein_panel',
    outerBounds: {
      width: 300,
      height: 800,
    },
  },
  function(createdWindow) {
    createdWindow.contentWindow.load_content = function(data) {
      createdWindow.contentWindow.document.getElementById('loading_content').appendChild(data);
    }
    new_panel = createdWindow;

    var deferred = $q.defer();
    deferred.resolve();
    console.log(deferred.promise)
    return deferred.promise;
  });
}

理论上,deferred.promise应该只有在resolved时才返回,但它就像then()函数在它真正发生之前就被执行了。为什么?

UPDATE2:或另一种方法来做同样的事情(也不起作用)

one();

function one() {
  chrome.app.window.create('empty.html', 
  {
    id: 'protein_panel',
    outerBounds: {
      width: 300,
      height: 800,
    },
  },
  function(createdWindow) {
    createdWindow.contentWindow.load_content = function(data) {
      createdWindow.contentWindow.document.getElementById('loading_content').appendChild(data);
    }
    new_panel = createdWindow;

    var deferred = $q.defer();
    deferred.resolve();
    console.log('first '+deferred.promise)
    return deferred.promise;
  }).then(function() {
    console.log('second')
    new_panel.contentWindow.load_content(something);
  });
}

日志 'second' 在 'first' 之前打印。代码有问题吗?

您想同步 return 来自 one() 的承诺,并在创建后用新的 window 解决承诺:

one().then(function(createdWindow) {
  // Window has been created
  createdWindow.contentWindow.load_content(something);
})

function one() {
  // create a promise
  var deferred = $q.defer();

  chrome.app.window.create('empty.html', 
  {
    id: 'protein_panel',
    outerBounds: {
      width: 300,
      height: 800,
    },
  },
  function(createdWindow) {
     // resolve our promise and pass the window to the `then` block
     deferred.resolve(createdWindow)
  });

  // synchronously return a promise
  return deferred.promise;
}