节点js在循环执行之前返回

时间:2018-01-28 16:41:30

标签: javascript node.js

我是节点js的新手,在我的项目中,其中一个函数不等待循环执行

let prepareExecution = (type) => {
 let files = [];
 let filestodelete = [];
 let data = {};
 data.files = files;
 data.filestodelete = filestodelete;
 let list = ['vpl_run.sh','vpl_debug.sh', 'vpl_evaluate.sh', 'vpl_evaluate.cases'];
 for (let i = 0, len = list.length; i < len; i++) {
  let fileName = list[i];
  let testCase = "Case1";
  let test = {};
  test[fileName] = testCase;
  console.log(test)
  data.files.push(test);
 }
 let test = {};
 test.fileName = 1;
 data.filestodelete.push(test);
 return data;
}

我得到的是

{
  "files": {},
  "filestodelete": {
    "fileName": 1
  }
}

我需要的输出是

{
 "files": { 'vpl_run.sh': 'Case1'},
 "filestodelete": {
   "fileName": 1
  }
}

你可以请任何人指导我解决上述问题

1 个答案:

答案 0 :(得分:0)

我稍微重写了你的代码,因为所有冗余变量都让我感到恼火,

let prepareExecution = (type) => {
 let data = {};
 data.files = [];
 data.filestodelete = [];
 let list = ['vpl_run.sh','vpl_debug.sh', 'vpl_evaluate.sh', 'vpl_evaluate.cases'];
 for (let i = 0, len = list.length; i < len; i++) {
  let fileName = list[i];
  let test = {};
  test[fileName] = "Case1";
  console.log(test);
  data.files.push(test);
 }
 let test = {};
 test.fileName = 1;
 data.filestodelete.push(test);
 return data;
}

但你问题中的函数和这个函数都返回

{ files:
   [ { 'vpl_run.sh': 'Case1' },
     { 'vpl_debug.sh': 'Case1' },
     { 'vpl_evaluate.sh': 'Case1' },
     { 'vpl_evaluate.cases': 'Case1' } ],
  filestodelete: [ { fileName: 1 } ] }

当我在节点v7.4.0中运行它们时