我遇到的情况是,一堆函数需要等待承诺解决,因为它是 init 函数;
self.init=new Promise(function(resolve){
//do stuff, take awhile
resolve();
});
但是,当它正在初始化时,异步性质意味着依赖于它的其他函数正在被调用。我希望这些函数等待 init 完成,然后继续。
我尝试在每个函数中执行此操作
function doSomethingUseful(){
self.init.reflect().then(function () {
//do functions purpose
});
}
function doSomethingUseless(){
self.init.reflect().then(function () {
//do functions purpose
});
}
但它只能随机工作,可能只有在 init 已经解决的情况下才有效,如果没有解决,它就会挂在这里,奇怪地挂起整个应用程序,尽管它是异步的。
我正在尝试替换以前的解决方案,该解决方案涉及间隔并在每个函数调用中检查布尔 isInit。
有没有蓝鸟函数可以做到这一点?或者另一种继续等待并检查承诺以查看其是否得到解决的方法?
该应用程序在很多地方都有这种结构。通常围绕 sqlite 读/写。用于打开数据库的 init,但在打开时,页面正在加载,并且它已经在尝试读/写表,因此通过使用 setInterval 并重复检查 init 是否完成来强制这些读/写等待。
这是一个使用谷歌分析的例子。
function Analytics() {
var self = this;
self.ready = ko.observable(false).subscribeTo('application:ready'); //attached to page ready event in jquerymobile and cordova
self.trackerInit = new Promise(function (resolve, reject) {
ko.computed(function () {
if (self.ready()) {
window.ga.startTrackerWithId('id', 1000, resolve, reject);
}
});
});
}
Analytics.prototype.trackSpeed = function (cat, interval, variable, label) {
var self = this;
console.log("speed tracker", cat, interval, variable, label); //this logs
return self.trackerInit.then(function () {
console.log("speed tracker confirm init"); //this never logs, all execution stops including other async code
return new Promise(function (resolve, reject) {
window.ga.trackTiming(cat, interval, variable, label, resolve, reject);
});
}).catch(function (e) {
if (e.message === "send timeout") {
return true; //who cares about timeouts anyways
} else {
throw e;//rethrow it
}
});
};
函数在页面更改事件中调用,没有返回,纯异步。调用它会导致所有执行停止。
准备好的ko就这样完成了
self.ready = ko.observable(false).publishOn('application:ready');
var deviceReady = new Promise(function (resolve) {
$(document).on('deviceready', resolve);
});
var pageReady = new Promise(function (resolve) {
$(document).on('pagecreate', resolve);
});
Promise.all([deviceReady, pageReady]).then(function () {
//a couple of page of code and...
self.ready(true);
});
在检查其结果时,像这样更改 init 会产生相同的挂起结果
self.trackerInit = new Promise(function (resolve, reject) {
console.log("initting");
checker = setInterval(function () {
if (window.ga) {
console.log("ready init");
window.ga.startTrackerWithId('id', 100, function(){
clearInterval(checker);
console.log("init complete");
resolve();
}, reject);
}
}, 1000);
});