我想创建一个窗口,并在创建它时运行一个已预加载的函数。我必须等到窗口被创建,否则该功能不可用并且失败。我想说我可以通过 promise 做到这一点。
怎么做呢?这是我尝试执行的代码
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 property 'then' of undefined
更新:稍微修改了代码,仍然不起作用,自从我使用它以来,我就使用了 Angular 的 promise
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 只应在解析时返回,但它就像 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”之前打印。代码有问题吗?
最佳答案
您希望从 one()
同步返回一个 Promise,并在创建新窗口后用新窗口解析该 Promise:
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;
}
关于javascript,在 Chrome Web 应用程序中创建窗口,如何包含成功调用新窗口函数的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32498252/