最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Execute a function after a map function - Stack Overflow

programmeradmin4浏览0评论

I have this code

$scope.items.map(function (item) {
   if(item.keywords.indexOf($scope.formData.keyword) != -1){
       array.push(bono);
   }
})

And I need to execute a function with all the elements of the array when the map finish. How can I do this? I thought to stack the calls but I don't know how to do it.

Thanks

I have this code

$scope.items.map(function (item) {
   if(item.keywords.indexOf($scope.formData.keyword) != -1){
       array.push(bono);
   }
})

And I need to execute a function with all the elements of the array when the map finish. How can I do this? I thought to stack the calls but I don't know how to do it.

Thanks

Share Improve this question asked Sep 11, 2015 at 8:35 David LuqueDavid Luque 1,1085 gold badges18 silver badges30 bronze badges 3
  • Just put it on the next line. – zerkms Commented Sep 11, 2015 at 8:39
  • It's angular, it's asynchronous :( – David Luque Commented Sep 11, 2015 at 8:39
  • 1 What exactly is asynchronous in this code? What type is $scope.items? – zerkms Commented Sep 11, 2015 at 8:41
Add a comment  | 

4 Answers 4

Reset to default 13

As soon as $scope.items is an array as you stated in the question and the Array.prototype.map() is synchronous - which means that you simply put the next statement after this code and it will be executed after the .map() has completed processing.

We can use Promise.all() function:

var promises = [obj1, obj2,objN].map(function(obj){
  return database.query('id').then(function(results){
     return results;
  })
})
Promise.all(promises).then(function(results) {
    console.log("Result",results);
})

try this:

var array = [];
$scope.items.map(function (item) {
   if(item.keywords.indexOf($scope.formData.keyword) != -1){
       array.push(item);
   }
});

myFunction(array);

Array.map() documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

try like this

$scope.items.map(function (item) {
   if(item.keywords.indexOf($scope.formData.keyword) != -1){
       array.push(bono);
   }
}).then(function(){}).then(function(){});
发布评论

评论列表(0)

  1. 暂无评论