简体   繁体   中英

Angular Promise, why am I getting 'then' of undefined in this instance?

I have a function in my chartDirective which makes a call to a function in a service to GET data, format that data then call another function from my 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;
    });
}

However I am getting the following error on the following line: 在此处输入图片说明

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

Here is my FormatChartDataFactory.getData function:

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') {
                // ....

Here is the link to my full FormatChartDataFactory gist file .

Promise should be return from code directly, it shouldn't be return from the .then callback of it. In short you have not returned promise from function and you are looking for .then method there, which results into an error.

Code

//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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM