Promise.map没有返回正确的顺序

时间:2018-03-28 20:23:37

标签: angularjs asynchronous promise bluebird

使用蓝鸟我怎样才能完成以下工作。

 groupCast = [Promise.resolve("name1"), Promise.resolve("name2"),Promise.resolve("name3")]

    Promise.map( groupCast , function (group){
        Promise.resolve($http.get("/getdata" , params:{group:group}))
               .then(function(response){ console.log(group," done")return response}))
        return response

        })
              .then(function(resp){console.log(resp)})

如果http呼叫的每个组的响应是“一个”,“两个”,“三个” 我们希望有:

"name1 done";
"name2 done";
"name3 done";
[ "one" , "two" ,"three" ]

但是我得到了

 [ "one" , "two" ,"three" ]
    "name1 done";
    "name2 done";
    "name3 done";

我该怎么办?我不能使用异步并等待,因为IE不支持。

1 个答案:

答案 0 :(得分:3)

首先,您的代码格式化使得有点难以看到正在发生的事情。让我清理一下并添加一些评论,这样你就可以看到发生了什么。

    class Course {
    private String courseName;
    private String[] students = new String[100];
    private int numberOfStudents;

    public Course(String courseName) {
        this.courseName = courseName;
    }
    public void addStudent(String student) {
        int add = numberOfStudents - students.length; //Create integer to find how many slots we need
        if (numberOfStudents > students.length) {  //if # of students is bigger then size of array,
            String[] array = new String[students.length + add]; //then we add slots to the array.
            System.arraycopy(students, 0, array, 0, students.length); //copy array
            students = array;
        }
        students[numberOfStudents++] = student; //add student.
    }
    public String[] getStudents() {
        return students;
    }
    public int getNumberOfStudents() {
        return numberOfStudents;
    }
    public String getCourseName() {
        return courseName;
    }
    public void dropStudent(String student) {
        for (int i = 0; i < students.length; i++) {
            if (student == (students[i])) { //If student matches the student we want to remove.
                numberOfStudents--; //remove student
            while (i < numberOfStudents) {
                students[i] = students[i+1];
                        i++;
            }
          }
        }
     }
    public void clear() {
        students = new String[1];  //set size to 1
        numberOfStudents--; //remove all students
    }
}

现在让我们解决它,以便承诺正确链接。

Promise.map(groupCast, function(group) {
  //the following kicks off a new promise, which is not chained to the current one
  Promise.resolve($http.get("/getdata", { params: { group: group } })).then(
    function(response) {
      console.log(group, " done");
      //you're returning response below, but it's not going anywhere!
      return response;
    }
  );
  //The current promise resolves right away, not waiting for the $http call.
  //Also, you're returning an undefined value here.
  return response;
}).then(function(resp) {
  //the prior promise resolves with undefined.
  console.log(resp);
});