【问题标题】:Appending new Elements to Objects in Array将新元素附加到数组中的对象
【发布时间】:2017-08-05 03:14:13
【问题描述】:

几天来,我一直在为这个循环感到困惑,并不能完全得到我需要的东西。

我遍历我的搜索结果数组 (mdb_results) 并从每个对象中提取 .name 以用作 Google CSE 图像搜索中的 _search 术语。

CSE 返回另一个数组 (cse),我想将它附加到从中提取 _search 术语 (mdb_results[i]) 的对象中。

router.get('/json', function(req, res, next) {
var ImageSearch = require('node-google-image-search');
MongoClient.connect(url, function(err,db){
  db.collection('mycatalog')
    .find({$text: {$search:"FOO" }})
    .toArray(function(err, mdb_results){    
        for (var i=0; i<mdb_results.length; i++){           
            var _search =  mdb_results[i].name ;

            ImageSearch(_search, function(cse){

               // How to add cse.img to mdb_results[i].images ??
               //    mdb_results[i].images = cse;
               // gives undefined

            },0,2);  
        };
        res.send(mdb_results);
        });
    });
});

我最初的mdb_results 看起来像这样。

[{"name":"FOO"},{"name":"FOOOO"}]

我正在努力实现这样的目标,

[{"name":"FOO", 
  "images":[{"img1":"http://thumbnail1"},{"img2":"http://thumbnail2"}]
},
{"name":"FOOOO", 
  "images":[{"img1":"http://thumbnaila"},{"img2":"http://thumbnailb"}]
}]

谁能告诉我如何做到这一点?

谢谢

【问题讨论】:

    标签: javascript node.js loops asynchronous google-custom-search


    【解决方案1】:

    问题是您期望异步操作同步工作:

    router.get('/json', function(req, res, next) {
    var ImageSearch = require('node-google-image-search');
    MongoClient.connect(url, function(err,db){
      db.collection('mycatalog')
        .find({$text: {$search:"FOO" }})
        .toArray(function(err, mdb_results){    
            for (var i=0; i<mdb_results.length; i++){           
                var _search =  mdb_results[i].name ;
                // This search is asynchronous, it won't have returned by the time
                // you return the result below.
                ImageSearch(_search, function(cse){
    
                   // How to add cse.img to mdb_results[i].images ??
                   //    mdb_results[i].images = cse;
                   // gives undefined
    
                },0,2);  
            };
            // At this point, ImageSearch has been called, but has not returned results.
            res.send(mdb_results);
            });
        });
    });
    

    您将需要使用 Promise 或 async 库。

    这是一个例子:

    router.get('/json', function(req, res, next) {
    var ImageSearch = require('node-google-image-search');
    MongoClient.connect(url, function(err,db){
      db.collection('mycatalog')
        .find({$text: {$search:"FOO" }})
        .toArray(function(err, mdb_results){
            // async.forEach will iterate through an array and perform an asynchronous action.
            // It waits for you to call callback() to indicate that you are done
            // rather than waiting for it to execute synchronously.
            async.forEach(mdb_results, function (result, callback) {
                ImageSearch(result.name, function(cse){
                   // This code doesn't get executed until the network call returns results.
                   result.images = cse;
                   // This indicate that you are done with this iteration.
                   return callback();
                },0,2);  
            },
            // This gets call once callback() is called for each element in the array,
            // so this only gets fired after ImageSearch returns you results.
            function (err) {
                res.send(mdb_results);
            });
        });
    });
    

    【讨论】:

    • 这行得通,我接受了你的回答 - 谢谢。您介意详细说明cb 的情况吗?尽管它有效,但我很难理解发生了什么。
    • 我更新了帖子以尝试详细说明。了解回调如何在 NodeJS 中工作对于了解这里发生的事情至关重要。回调用于指示您已完成工作。
    • 感谢您的注释。我还在为return callback() 而苦苦挣扎,这似乎是对自己的呼唤?我们将callback 传递到封闭函数中,然后在没有callback 的任何函数定义的情况下调用它。如果答案太复杂而无法发表评论,您能推荐一个我可以自学的资源吗?
    • This article covers the content. 您提供了一个函数,该函数将结果和回调作为参数。回调是异步库传入的函数。异步等待您调用该函数以确认您已完成异步工作。一旦你在每次迭代中调用了callback(),Async 就知道你已经完成了。如果您需要更多信息,请查找有关 Nodejs 回调的更多文章。很难理解,但对 Nodejs 编程至关重要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2018-09-02
    • 1970-01-01
    相关资源
    最近更新 更多