使 JavaScript 方法等待构造函数完成 [英] Make JavaScript method wait for constructor to complete

查看:66
本文介绍了使 JavaScript 方法等待构造函数完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构造函数需要一些时间,在调用方法时,this.folders 尚未定义.如何让 getIt() 等到构造函数完成?

The constructor takes some time, and when the method is called, this.folders is not yet defined. How do I allow getIt() to wait until the constructor is complete?

function test() {
    var t=this;
    $.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
        t.folders=returned;
    });
}
test.prototype.getIt = function() {
    return this.folders;
};

var myObj = new test();
console.log(myObj.getIt());

推荐答案

由于 $.getJSON() 是异步的,所以没有办法阻止 test() 从填充 t.folders 后返回.

Since $.getJSON() is asynchronous, there is no way of preveting test() from returning after t.folders is populated.

您可以使用回调:

function test(callback) {
    $.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
        callback(returned);
    });
}

var myObj = new test(function (folders) {
    console.log(folders);
});

或者一个承诺(在这个例子中,使用 Q 库):

Or a promise (in this example, using Q library):

function test() {
    var t = this;
    t.folders = Q.defer();

    $.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
        t.folders.resolve(returned);
    });
}
test.prototype.getIt = function() {
    return this.folders.promise;
};

var myObj = new test();
myObj.getIt().done(function (folders) {
    console.log(folders);
});

这篇关于使 JavaScript 方法等待构造函数完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆