让Cordova等待异步钩完成 [英] Make Cordova wait for async hook to finish
问题描述
在我的Cordova项目中,我有一个钩子在 after_prepare
上执行RequireJS优化(r.js)。该优化本质上是异步的,因此我的挂钩代码会在所有优化完全完成之前返回。
In my Cordova project, I have a hook which does RequireJS optimization (r.js) on after_prepare
. That optimization is inherently asynchronous, so my hook code returns before all optimization is fully finished.
例如,这会在运行 cordova运行浏览器时引起问题
:在首页加载过程中,优化尚未完成,站点看上去也很破损。
For example, this causes issues when running cordova run browser
: On the first page load, optimization has not finished yet and the site looks broken.
是否有一种方法可以使Cordovoa构建过程阻止直到某个钩子触发回调?还是可以以阻塞/同步的方式运行优化器?
Is there a way to make the Cordovoa build process to block until a certain hook fires a callback? Or can the optimizer be run in a blocking/sync way?
我能想到的另一种方法是使用不同的过程进行优化,并在主进程中进行繁忙等待可以完成,但是对我来说似乎是一个矫kill过正和不好的做法。
An alternative I could think of is using a different process for optimization and busy-wait in the main for it to finish, but that looks like an overkill and bad practice to me.
推荐答案
您可以使用内置的promise模块来阻止Cordova继续进行,直到问题解决为止。
遵循以下原则:
You can use the built-in promise module to block Cordova from proceeding until the hook has resolved. Something along these lines:
#!/usr/bin/env node
var deferral;
function doSomethingAsync(){
somethingAync
.success(function(){
deferral.resolve();
})
.fail(function(err){
deferral.reject(err);
});
}
module.exports = function(ctx) {
deferral = ctx.requireCordovaModule('q').defer();
doSomethingAsync();
return deferral.promise;
};
这篇关于让Cordova等待异步钩完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!