传递数组作为引用类型node.js

时间:2018-01-23 09:15:12

标签: javascript arrays node.js

我正在连接S3并解析json文件,
我创建了一个名为Singer的新对象和一个对象数组。 我想在函数范围之外使用这个对象数组

console.log("Loading up the best code ever!!!");

var fs = require('fs');
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
var jsonfile = require('jsonfile')
var Singer = require('./Singer')
// Set the region 
AWS.config.update({ region: "us-west-1" });
var credentials = new AWS.SharedIniFileCredentials();
AWS.config.credentials = credentials;
// Create S3 service object
s3 = new AWS.S3({ apiVersion: '2006-03-01' });
console.log("after S3");


// Create the parameters for calling createBucket
var bucketParams = {
    Bucket: 'pc-backend-exercises',
    Key: 'toSearch.json',
    ResponseContentType: 'application/json'
};
s3.getObject(bucketParams, function (err, data) {
    // Handle any error and exit
    if (err) {
        console.log(err, err.stack); 
        return err;
    }
    var fileContents = data.Body.toString();
    var json = JSON.parse(fileContents);
    console.log(json);

    var singers = [];
    for (var i = 0; i < json.Search.artists.length; i++) {
        var newSinger = new Singer(json.Search.artists[i]);
        singers.push(newSinger);
    }


    console.log('Singers:');
    console.log(singers);


});

console.log('download json file from s3');

此代码工作正常。我得到了输出

Loading up the best code ever!!!
after S3
download json file from s3
{ Search: { artists: [ 'Katy', 'Madonna', 'Rihanna', 'Beyonce' ] } }
Singers:
[ Singer { name: 'Katy', songs: [] },
  Singer { name: 'Madonna', songs: [] },
  Singer { name: 'Rihanna', songs: [] },
  Singer { name: 'Beyonce', songs: [] } ]

然而我改变我的代码以通过引用来传递数组歌手并不起作用。

var singers = [];
s3.getObject(bucketParams, function (err, data, singers) {
    // Handle any error and exit
    if (err) {
        console.log(err, err.stack); 
        return err;
    }
    var fileContents = data.Body.toString();
    var json = JSON.parse(fileContents);
    console.log(json);


    for (var i = 0; i < json.Search.artists.length; i++) {
        var newSinger = new Singer(json.Search.artists[i]);
        singers.push(newSinger);
    }

});

console.log('Singers:');
console.log(singers);


console.log('download json file from s3');

输出是:

Loading up the best code ever!!!
after S3
Singers:
[]
download json file from s3
{ Search: { artists: [ 'Katy', 'Madonna', 'Rihanna', 'Beyonce' ] } }
C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\request.js:31
            throw err;
            ^

    TypeError: Cannot read property 'push' of undefined
        at Response.<anonymous> (C:\Users\gdarmon\Desktop\Node\gili.js:38:17)
        at Request.<anonymous> (C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\request.js:364:18)
        at Request.callListeners (C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\sequential_executor.js:105:20)
        at Request.emit (C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\sequential_executor.js:77:10)
        at Request.emit (C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\request.js:683:14)
        at Request.transition (C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\request.js:22:10)
        at AcceptorStateMachine.runTo (C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\state_machine.js:14:12)
        at C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\state_machine.js:26:10
        at Request.<anonymous> (C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\request.js:38:9)
        at Request.<anonymous> (C:\Users\gdarmon\Desktop\Node\node_modules\aws-sdk\lib\request.js:685:12)

你能帮忙吗?

2 个答案:

答案 0 :(得分:1)

这里有两个问题。

错误消息

  

无法读取未定义的属性'push'

看这里:

s3.getObject(bucketParams, function (err, data, singers) {

singers未定义,因为您已定义了一个名为singers的参数(它在更宽的范围内屏蔽了该变量)。 getObject函数在调用传递给它的匿名函数时,不会给第三个参数赋值。

我不知道你为什么期望它。

如果删除该参数,则可以再次访问更广泛范围内的singers变量。

执行顺序

这是常见问题解答。请参阅所有Stackoverflow上可能位于前三个目标中的How do I return the response from an asynchronous call?

答案 1 :(得分:0)

问题在于变量的范围。 您已在本地和全局定义了相同的变量名称。

更改本地变量名称,它应该有效我将更改为singers1

var singers = [];
s3.getObject(bucketParams, function (err, data, singers1) {