简体   繁体   中英

How to call function itself inside a function in my case

I am trying to call the function itself within the function.

Basically it will call the function itself to make another request if the first request has the id.

I have something like

function test(variable) {
    var q = $q.defer();
    $http({
           method: 'get',
           url: 'myurl.com'
        }).then(function(returnData) {
            if(returnData.getNewInfo) {
                test(returnData.id).then(function(secondData){
                   q.resolve(secondData);
                })
            } else {
                   q.resolve(returnData)
            }    
        });            
    }
    return q.promise;
}

I am getting test(...).then is not a function error in the console on this line

 test(returnData.id).then(function(secondData){

I am trying to call the function itself inside the promise. Not sure how to fix my issue. Can anyone help me about it? Thanks a lot!

Fix your code indentation and you'll get the below - see my comment about the stray brace. So the function is returning undefined rather than q.promise .

function test(variable) {
    var q = $q.defer();
    $http({
        method: 'get',
        url: 'myurl.com'
    }).then(function(returnData) {
        if (returnData.getNewInfo) {
            test(returnData.id).then(function(secondData) {
                q.resolve(secondData);
            })
        } else {
            q.resolve(returnData)
        }
    });
}  // <------- end of function - should be removed?

return q.promise;
}

You can return your $http call. Promises are chainable and $http returns a promise.

function test(variable) {
    return $http({
        method: 'get',
        url: 'myurl.com'
    }).then(function (returnData) {
        if (returnData.getNewInfo) {
            return test(returnData.id);
        } else {
            return returnData;
        }
    });
}

Try this:

function test(variable, callback) {
  /*snip*/
  callback();
  /*snip*/
}
test("foo",test);

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