完成HTTP请求循环后,将执行下一个函数

时间:2018-02-09 09:31:51

标签: javascript node.js typescript ionic-framework

  

我需要在完成HTTP请求循环后调用下一个函数   请求数取决于输入的数量。

我尝试使用承诺来确保所有HTTP请求都已完成。 但它不起作用..我不知道如何解决这个问题......

checkWords(){
let promise = new Promise(function (onFulfilled, onRejected) {

  let input = "Words for send request";
  let words = ['A', 'B', 'C', 'D', 'E', 'F'];
  let wordsCount = [0, 0, 0, 0, 0, 0];
  let inputSplitted = input.split(" ", ms.length);

  for (let i = 0; i < inputSplitted.length; i++) {

    this.http.get("url + inputSplitted , options)
      .subscribe(res => {

        // content is a string that contain a word of A/B/C/D/E or F
        let content = res['_body'].entryContent
        let wordlevelIndex = 0 // For indexing "words" array
        let lvlfound = false

        while (!lvlfound) {
          // Index of the string A,B,C,D,E,F in the respond
          let strIndex = content.search(words[wordlevelIndex])
          if (strIndex == -1) { // -1 = not found A,B,C,D,E,F
            wordlevelIndex++
          } else {

            // Substring that respond for getting string A,B,C,D,E,F
            let lvlIndex = content.substring(strIndex, strIndex + 1);
            console.log(lvlIndex)

            // Count the word that found
            if (lvlIndex == words[0]){
              wordsCount[0]++
            }else if (lvlIndex == words[1]){
              wordsCount[1]++
            }else if (lvlIndex == words[2]){
              wordsCount[2]++
            }else if (lvlIndex == words[3]){
              wordsCount[3]++
            }else if (lvlIndex == words[4]){
              wordsCount[4]++
            }else if (lvlIndex == words[5]){
              wordsCount[5]++
            }
            lvlfound = true
            wordlevelIndex++
          }
        }
      });
  }
  onFulfilled([wordsCount[0], wordsCount[1], wordsCount[2], wordsCount[3], wordsCount[4], wordsCount[5]]);
  onRejected('Error');
})

promise.then(([arg0, arg1, arg2, arg3, arg4, arg5]) => {
    this.countA += arg0
    this.countB += arg1
    this.countC += arg2
    this.countD += arg3
    this.countE += arg4
    this.countF += arg5
});
    return promise
}

我需要在 checkFirst()函数中运行此函数,并使用 Promise.all 函数进行检查..

然后,这是我的HTTP请求代码......

-p 5433: 5432

使用这些代码,我仍然有一个异步的功能,它调用&#34; this.doSomething&#34;在所有请求完成之前。我只希望在使用下一个函数之前完成所有响应。我是否通过使用Promise做错了什么?请帮帮我。感谢。

1 个答案:

答案 0 :(得分:0)

您在解决请求之前立即解决(并拒绝!)承诺,在呼叫返回之前。我认为解决方案(您的onFulfilled调用)应该放在subscribe参数函数的末尾。