0

How to return value after timeout in this function

$get: function($timeout) {
        var breadcrumbs;
        data = [];

        $timeout(function() {
          data = crateBreadcrumbs();
          console.log(data);
        });
        return data;
Sibiraj
  • 4,486
  • 7
  • 33
  • 57

1 Answers1

2

You need to return a promise. The promise will signify that you have not yet returned data, but you will resolve that promise once your $timeout service is completed.

You can use the $q service to achieve this. docs

Essentially,

function($timeout) {
    var deferred = $q.defer();

    $timeout(function() {
        data = createBreadcrumbs();
        deferred.resolve(data);
    }, 1000);

    return deferred.promise;
}

Per @Bergi's comment,

$get: function($timeout) {
    return $timeout(function() { return createBreadcrumbs();})
}
alexhuang
  • 506
  • 1
  • 3
  • 12
  • 3
    `$timeout` already returns a promise. Avoid the [deferred antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jul 06 '17 at 08:13
  • thanks alex and @Bergi – Sibiraj Jul 06 '17 at 08:42