只有在主干javascript fetch()调用完成后才需要运行代码

时间:2014-10-04 09:41:11

标签: javascript jquery backbone.js

在下面的代码中,我尝试在true块中将test2()test1()返回到if
test2()中,变量flagtrue fetch()块中设置为success, 现在的问题是,由于主干fetch()异步调用,test2()正在将false返回到test1() if块(因为这样在{ {1}})以及之后,ajax调用完成后test1() test2()success设置为flag但这没有用,因为它已经返回{{1转到true

所以,请告诉我,只有在fetch false块中设置了test1()值时,如何在test2()中阻止任何延迟/或运行 我尝试使用flagsuccess但不适合我。 请帮助解决这个问题,因为我已经花了很多天但却无法解决这个问题。

_.delay()

谢谢!

2 个答案:

答案 0 :(得分:0)

您无法通过异步调用返回Boolean

您最好使用sync回调来运行test1

this.listenTo(CaseTeam, 'sync', test1);

CaseTeam应该在您的代码中可用。

如果您提供简化的测试用例,我会改进我的答案。

答案 1 :(得分:0)

您需要的只是了解JQuery承诺如何工作:http://code.tutsplus.com/tutorials/wrangle-async-tasks-with-jquery-promises--net-24135

test1 :function()
{
    var x = true;

    // Call test2() and wait it
    this.test2().done(function (response) {
        if (x) {
            // run the code here
        }
    });
},

test2: function()
{ 
    var noteCaseTeam = App.data.createBean('Module',{id:123});//Return the object of Team  
    return noteCaseTeam.fetch().done(
        function(response) {
            case_number_team  = noteCaseTeam.get('name');
        }
    );
},