javascript-将集合而不是数组传递给fetch().then()回调

从服务器获取数据并返回Promise的模块

MedicineManager.module("Entities", function (Entities, MedicineManager, Backbone, Marionette, $, _) {
    Entities.Suggestion = Backbone.Model.extend({
        default: {
            suggestion: ""
        }
    });

    Entities.SuggestionCollection = Backbone.Collection.extend({
        model: Entities.Suggestion,
        comparator: "suggestion"
    });

    var API = {
        getSuggestions: function (medicine) {
            var suggestions = new Entities.SuggestionCollection();
            suggestions.url="/medicine_suggestions/?id=" + medicine;
            return suggestions.fetch();
        }
    };

    MedicineManager.reqres.setHandler("suggestion:entities", function (medicine) {
        return API.getSuggestions(medicine);
    });

});

调用上述模块以获取数据的模块

MedicineManager.module("MedicinesApp.Suggest", function (Suggest, MedicineManager,
    Backbone, Marionette, $, _) {


            MedicineManager.request("suggestion:entities", "paracetamol").then(function (medicines) {


            });
});

在then()中,如何获取集合而不是数组作为回调函数的参数,因为传递给回调的medicines参数在获取值后给出了数组.

解决方法:

filter it via .then不会直接返回xhr promise,而是将您的集合设置为承诺值:

var API = {
    getSuggestions: function (medicine) {
        var suggestions = new Entities.SuggestionCollection();
        suggestions.url="/medicine_suggestions/?id=" + medicine;
        return suggestions.fetch().then(function() {
            return suggestions;
        });
    }
};

MedicineManager.request(…).then(function(medicines){})中的第一个参数(医学);将是您的收藏.

上一篇:《python核心编程》读书笔记——列表解析


下一篇:JQuery的deferred.promise()