将新元素添加到数组中的对象

时间:2017-03-14 16:46:09

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

我一直在为这个循环感到困惑几天,并且不能完全满足我的需要。

我遍历我的搜索结果数组#!/usr/bin/perl use strict; use warnings; $^I = '.bak'; # create a backup copy while (<>) { s/HW/HT/g; # do the replacement s/OW/OT/g; # do a second replacement print; # print to the modified file } )并从每个对象中提取mdb_results以用作Google CSE图片搜索中的.name字词。

CSE返回另一个数组(_search),我想要追加到我从中提取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"}]

有人能告诉我如何实现这个目标吗?

由于

1 个答案:

答案 0 :(得分: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);
        });
    });
});

您需要使用promises或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);
        });
    });
});