user3374552
user3374552

Reputation: 3

Waiting for function execution

Is a function:

function getItem(key) {
    var item;
    func(key, function(items) {
        for (var key2 in items) {
            if (key2 === key && items.hasOwnProperty(key2)) {
                item = items[key2];
            }
        }
    });
    return item;
}

When we call it, the response we get undefined. How to wait for the callback function execution and only then return the result?

Upvotes: 0

Views: 80

Answers (2)

Andy
Andy

Reputation: 63514

Just introduce a callback as a parameter to your function:

function getItem(key, callback) {
  func(key, function(items) {
    for (var key2 in items) {
      if (key2 === key && items.hasOwnProperty(key2)) {
        callback(items[key2]);
      }
    }
  });
}

getItem('bob', function (key) {
  console.log(key);
});

Upvotes: 2

SergeS
SergeS

Reputation: 11779

You cannot. Thats all. Because Javascript have no way to wait for asynchronous callback.

You can reuse the concept of callbacks to return your value instead of returning it directly

function getItem(key, callback) {
  var item;
  func(key, function(items) {
    for (var key2 in items) {
      if (key2 === key && items.hasOwnProperty(key2)) {
        item = items[key2];
      }
    }

    callback(item);
  });
}

And then use it getItem('key', function( item ) { ... })

Upvotes: 1

Related Questions