Angular Promise,为什么我会得到'然后'在这个例子中未定义?

时间:2015-10-19 16:51:12

标签: javascript angularjs asynchronous promise angular-promise

我的chartDirective中有一个函数调用GET数据服务中的函数,格式化该数据然后调用我的chartDirective中的另一个函数:

function chartTicker(ticker, disabled) {
    disabled = disabled || false;
    var defer = $q.defer();

    // Clear out previous chart:
    d3.selectAll("svg > *").remove();
    document.getElementById('chart').innerHTML = "";
    chart     = {},
    chartData = [];

    // Get and format data for chart:
    document.getElementById('chart').innerHTML = "<svg></svg>";
    var timeInHours = TimeSpanFactory.getTimeHours();

    var promise = FormatChartDataFactory.getData(ticker, timeInHours).then(function() {
        defer.resolve();
        return defer.promise;
    });
}

但是我在以下行中收到以下错误: enter image description here

var promise = FormatChartDataFactory.getData(ticker, timeInHours).then(function() {

这是我的FormatChartDataFactory.getData功能:

function getData(ticker, limit) {
    var defer = $q.defer();
    chartObj.chartData = [{}];
    var limit_range = '';

    if (limit > 0) {
        limit_range = '?limit=' + limit;
    }

    getTickerPrice(ticker, limit_range).then(function() {
        defer.resolve();
        return defer.promise;
    });

    // GET Ticker data and return chartObj into drawChart:
    ////////////////////////////////////////////////////////////////////
    function getTickerPrice(ticker, limit_range) {
        return ApiFactory.getTickerQuotes(ticker.ticker, limit_range)
            .success(function(data, status, headers, config) {
                if (data.status === 'Success') {
                // ....

这是link to my full FormatChartDataFactory gist file

1 个答案:

答案 0 :(得分:2)

Promise应该直接从代码返回,它不应该从它的.then回调中返回。总之,你还没有从函数中返回promise,而你正在寻找.then方法,这会导致错误。

<强>代码

//1st place
var promise = FormatChartDataFactory.getData(ticker, timeInHours).then(function() {
    defer.resolve();
});
return defer.promise;

//2nd place
getTickerPrice(ticker, limit_range).then(function() {
    defer.resolve();
});
return defer.promise;