Angular Promises: Best Practices and Pros/Cons of Different Techniques

时间:2015-05-12 23:17:53

标签: javascript angularjs promise angular-promise

I'm learning Angular and I've come across two approaches to make calls that return promises. I'd like to know if one approach is better than the other and/or when you would use each.

First Technique:

    Log.Logger = new LoggerConfiguration()
        .WriteTo.ColoredConsole()
        .WriteTo.EventLog("LOGSOURCE", restrictedToMinimumLevel: LogEventLevel.Warning)
        .WriteTo.Email(connectionInfo: new EmailConnectionInfo()
        {
            EmailSubject = "App error",
            ToEmail = "support@company.com",
            MailServer = "smtp.office365.com",
            NetworkCredentials = new NetworkCredential("sender@company.com", "Password"),
            Port = 587,
            FromEmail = "sender@company.com", 
            EnableSsl = false

        },
        batchPostingLimit: 1,
        restrictedToMinimumLevel: LogEventLevel.Error)
        .CreateLogger();

Log.Error("Error message");

Second Technique:

function getSomeDataFromServer() {
    var deferred = $q.defer();

    if (myData) {
        // call to backend was previously made and myData is already loaded 
        deferred.resolve(myData);
    } else {
        // get data from server
        $http.get(my_url_endpoint).then(function(response) {
            // cacheResult() will set myData = response.data
            deferred.resolve(cacheResult(response));
        });
    }

    return deferred.promise;
}

1 个答案:

答案 0 :(得分:4)

Always prefer the second option. The first option is an anti-pattern typically seen when the developer doesn't fully understand the nature of promises. Deferred objects (Function getTotalReceived(valCell As Range) As Variant Application.Volatile Dim book As Workbook Set book = valCell.Parent.Parent If book.Name <> "SALES.xlsm" Then Exit Function Dim receivedWs As Worksheet, reportWs As Worksheet Dim items As Range Set reportWs = book.Worksheets("Report") Set receivedWs = book.Worksheets("Received") Dim myItem As String, index As Long myItem = valCell.Value Set items = receivedWs.Range("A:A") On Error Resume Next index = Application.Match(myItem, items, 0) If Err.Number = 13 Then GoTo QuitIt On Error GoTo 0 Dim lCol As Long, Qty As Double, mySumRange As Range Set mySumRange = receivedWs.Range(index & ":" & index) Qty = WorksheetFunction.Sum(mySumRange) QuitIt: getTotalReceived = Qty End Function ) are used when you have some asynchronous code that uses callbacks but needs to work with your promise based code.

Most asynchronous things you do in Angular return promises, so you would typically only use deferreds when working with a 3rd party library that relies on callbacks.

In this example, $http itself returns a promise, so creating a new deferred object is not necessary. Returning the $http promise itself is sufficient.