0
function process(hugedirectory) {

        var title = hugedirectory.getTitleEachFile().then(function(caption){            
            console.log(caption);
            return caption;
        });


        return title;       
    }

I have an AJAX call which calls this method but right now, it will return nothing.

console.log(caption) displays correct and expected value. However, this value is not returned at the end of this method.

KJW
  • 15,035
  • 47
  • 137
  • 243

1 Answers1

3

Since process make use of asynchronous function calls, you cannot return a value from the method.

The solution to this kind of problem is to make use of callback functions as given below

function process(hugedirectory, callback) {
    hugedirectory.getTitleEachFile().then(function(caption){            
        console.log(caption);
        callback(caption)
    });
}

process(hugedirectory, function(title){
    //Do something with title
})

In this instead of returning the title from process we pass a callback function to process which is getting called when the async call is completed and the resulted title value is passed to the callback function.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • "Since process make use of asynchronous function calls, you cannot return a value from the method". This statement is not correct. A basic understanding of Deferreds/Promises should lead you re reconsider. – Beetroot-Beetroot Mar 25 '13 at 21:42
  • Arun, whereas your solution is perfectly OK, returning a promise from the function is also a viable approach. For example, the function could be as simple as `function process(hugedirectory) { return hugedirectory.getTitleEachFile(); }` and everything concerning `title` could be specified in standard blocked-code, `process(hugedirectory).then(function(title) { console.log(title); }).then(function(title) { /*Do something with title*/ }); `. I've stuck with `.then()` here though `.done()` (once or twice) would have the same effect. – Beetroot-Beetroot Mar 26 '13 at 00:58