Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Q.js顺序返回循环GET请求_Javascript_Node.js_Asynchronous_Q_Deferred - Fatal编程技术网

Javascript 使用Q.js顺序返回循环GET请求

Javascript 使用Q.js顺序返回循环GET请求,javascript,node.js,asynchronous,q,deferred,Javascript,Node.js,Asynchronous,Q,Deferred,我的主要职能如下: function main(body) { var deferred = Q.defer(); // Make an API request console.log("body :"+ body); var jsonbody = JSON.parse(body); partialSequence = jsonbody['partialSequence']; uniqID = jsonbody['uniq']; res

我的主要职能如下:

function main(body) {
    var deferred = Q.defer();
    // Make an API request
    console.log("body :"+ body);

    var jsonbody = JSON.parse(body);
    partialSequence = jsonbody['partialSequence'];
    uniqID =  jsonbody['uniq'];
    resultLength = jsonbody['resultLength'];

    console.log("resultLength :"+ resultLength);

    if (partialSequence.indexOf("G") > -1) ns.push("G");
    if (partialSequence.indexOf("A") > -1) ns.push("A");
    if (partialSequence.indexOf("C") > -1) ns.push("C");
    if (partialSequence.indexOf("T") > -1) ns.push("T");

    uniq = uniqID;
    var sequence = Promise.resolve();

    for (var i = 0; i < resultLength; i++) {
      location = i;
      for (var j = 0; j < nuclides.length; j++) {

        n = nuclides[j]

        var promise = getLocation(n, location, uniq);
        promise.then(function(values) {
          console.log("location :"+values[0] + " "+ values[1]);
          if (expressed) {
            isExpressed = true;
            if(route > 0) {
              for (var key in resultSeq) {
                if (resultSeq.hasOwnProperty(key)) {
                  var temp = resultSeq[key]
                  delete resultSeq[key];
                  temp = temp.concat(n);
                  resultSeq[temp] = temp;
                }
              }
            } else {
              resultSeq[n] = n;
            }
          }
        });
      }
      if (isExpressed) route++; //used to check if we append to existing sequences.
    }
    deferred.resolve();
    return deferred.promise
}

function getLocation(n, location, uniq) {
  var expressed
  var deferred = Q.defer();
  Q.ninvoke(request, 'get', {
    url:         "https://myapi.com/location?"+"location="+location+"&"+"nucleotide="+n+"&"+"uniq=    "+uniq
  }).spread(function(response, body) {
    expressed=1;
    var jsonbody = JSON.parse(body);
    return [jsonbody["expressed"], location];
  });

  return deferred.promise
}
功能主体(主体){
var deferred=Q.deferred();
//发出API请求
console.log(“body:+body”);
var jsonbody=JSON.parse(body);
partialSequence=jsonbody['partialSequence'];
uniqID=jsonbody['uniq'];
resultLength=jsonbody['resultLength'];
日志(“resultLength:+resultLength”);
如果(部分序列索引(“G”)>-1)ns.push(“G”);
如果(部分序列索引(“A”)>-1)ns.push(“A”);
如果(部分序列索引(“C”)>-1)ns.push(“C”);
如果(部分序列索引(“T”)>-1)ns.push(“T”);
uniq=uniqID;
var sequence=Promise.resolve();
对于(var i=0;i0){
for(在resultSeq中输入变量){
if(resultSeq.hasOwnProperty(键)){
var temp=resultSeq[键]
删除resultSeq[键];
温度=温度混凝土(n);
结果seq[temp]=temp;
}
}
}否则{
结果Q[n]=n;
}
}
});
}
if(isExpressed)route++;//用于检查是否附加到现有序列。
}
延迟。解决();
延期退换货
}
函数getLocation(n,location,uniq){
变量表示
var deferred=Q.deferred();
Q.ninvoke(请求“获取”{
url:“https://myapi.com/location?“+”位置=“+location+”&“+”核苷酸=“+n+”&“+”uniq=“+uniq
}).扩散(功能(响应、主体){
表达式=1;
var jsonbody=JSON.parse(body);
返回[jsonbody[“expressed”],位置];
});
延期退换货
}

当I console.log时,位置
值[0]
在应为0,1,2时出现故障…….n。我怎样才能做到这一点?非常感谢

首先,让我们简化
for
的内部循环,将该代码放入一个传递位置索引的函数中,然后在完成代码时返回一个新的承诺。因为您只是在处理数组的内容,所以可以使用
.reduce()
设计模式为每个数组元素链接承诺。这将以串行方式执行它们:

function innerWork(locationIndex) {
    // process the nuclides array for a given locationIndex
    return nuclides.reduce(function (p, n) {
        return p.then(function () {
            // now process a single locationIndex
            return getLocation(n, locationIndex, uniq).then(function (values) {
                console.log("location :" + values[0] + " " + values[1]);
                if (expressed) {
                    isExpressed = true;
                    if (route > 0) {
                        for (var key in resultSeq) {
                            if (resultSeq.hasOwnProperty(key)) {
                                var temp = resultSeq[key]
                                delete resultSeq[key];
                                temp = temp.concat(n);
                                resultSeq[temp] = temp;
                            }
                        }
                    } else {
                        resultSeq[n] = n;
                    }
                }
            });
        });
    }, Promise.resolve());
}
然后,只需手动链接到单个承诺即可完成外部循环,如下所示:

var sequence = Promise.resolve();
for (var i = 0; i < resultLength; i++) {
    (function(index) {
        sequence = sequence.then(function() {
            return innerWork(index);
        });
    })(i);
}
另外,请记住其他问题/答案中改进的
getLocation()
函数:

function getLocation(n, location, uniq) {
  var expressed
  return Q.ninvoke(request, 'get', {
    url:         "https://myapi.com/location?"+"location="+location+"&"+"nucleotide="+n+"&"+"uniq=    "+uniq
  }).spread(function(response, body) {
    expressed = 1;
    var jsonbody = JSON.parse(body);
    return [jsonbody["expressed"], location];
  });
}    

另外,您的原始代码有几个您正在引用的未声明变量。请确保所有变量都在适当的范围内声明。例如,我不知道您的
main()
函数中的
expressed
变量在哪里声明,并且有许多变量在您引用的
main()
中我没有看到本地声明。这通常是一种不好的做法。

当结果全部完成时,您是否只需要按顺序排列结果?如果是这样的话,可以用少量代码并行发送请求(比顺序请求快得多),以确保结果保持有序。此外,您的代码没有使用
j
。请您展示足够的代码,以便我们理解为什么存在
j
循环,因为这与如何最好地解决问题有关。@jfriend00我添加了更多的上下文。我需要按顺序返回GET请求,因为之前的每个迭代都是在前一个迭代的基础上生成的,因此它不能是随机顺序。请在此回答中使用
.reduce()
查看这两个选项:,这一条:.@jfriend00感谢这些链接,我认为这很有帮助,但有一点我不确定,那就是它们链接使用reduce,这意味着它使用数组。我如何使用for循环模拟相同的迭代。我可以用什么来代替减量?
function getLocation(n, location, uniq) {
  var expressed
  return Q.ninvoke(request, 'get', {
    url:         "https://myapi.com/location?"+"location="+location+"&"+"nucleotide="+n+"&"+"uniq=    "+uniq
  }).spread(function(response, body) {
    expressed = 1;
    var jsonbody = JSON.parse(body);
    return [jsonbody["expressed"], location];
  });
}