如何在强制数据的ajax请求中使用promises?

时间:2016-03-17 19:47:22

标签: javascript jquery ajax

我有一个脚本可以加载其他数据,并为视图的多个元素提供额外的功能。 我喜欢采取更多的OPP方法来做到这一点,所以我有"类"为我的实体构建。我现在面临的问题是信息来自服务器端,所以在我可以提供功能之前我需要这些数据。

在我的脚本上我有三个对象 User,Prospect and ProspectDetailView。

所以我以这种方式工作。

int totalElementsInArray = 0;

totalElementsInarray = IntStream.of(my2DArray[0 through 16][0]).sum();

如您所见,创建一个用户然后创建一个Prospect并最终加载我的View对象。

问题是我在使用视图之前需要潜在客户的数据(必填)。

我像这样加载我的潜在客户

extension NSDate {
    func dateWithTime(hour: Int, minute: Int, second: Int) -> NSDate? {
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let components = calendar.components(([.Day, .Month, .Year]), fromDate: self)
        components.hour = hour
        components.minute = minute
        components.second = second
        let newDate = calendar.dateFromComponents(components)
        return newDate
    }
}

我需要使用async false才能在我可以在视图对象中使用它之前检索潜在客户数据,并且它可以工作,但是不能让人感觉它是一个讨厌的黑客或错误

所以我尝试使用$ .when(我猜的是承诺)

并且这样做了:

$(document).ready(function _document_ready() 
{

//*
ajaxStatus.showStatus('Cargando información adicional...');
var promotor        = new User();
var prospecto       = new Prospect($("input[name=record]").val());
var vistaDetalle    = new ProspectDetailView();



vistaDetalle.drawAditionalStatusTag(prospecto.data);
vistaDetalle.drawGroupDataField(prospecto.inscription);
vistaDetalle.drawInscriptionDifferences(prospecto.data, prospecto.inscription);
vistaDetalle.drawPendingRequestTag(prospecto.inscription.requests);
vistaDetalle.drawPendingTicketTag(prospecto.inscription.tickets);
vistaDetalle.drawTicketsHistoryPanel(prospecto.inscription.tickets_h);

ajaxStatus.hideStatus();
//*/ 
});//#END _document_ready()

希望视图将在潜在客户和用户完成加载时执行但我失败了。 我犯了同样的错误 。 prospecto未定义,因为一切都是异步的。

我应该如何建模呢?据我所知,我需要直接将ajax调用传递给$ .when方法,但这样做会使我的实体分离并相互隔离。

1 个答案:

答案 0 :(得分:0)

你可以使用Promise。

var prospect_created = new Promise(function(resolve, reject){
    // any necessary setup
    $.ajax({
        success: resolve,
        error: reject,
       // etc
     })
})

create_prospect.then(function(prospect){
 // create your view using the prospect
})

通过将resolve作为success参数传递给ajax请求,从ajax请求返回的任何内容都将是传递给promise对象的.then方法的函数的参数。