等待“.then”解决

时间:2017-07-13 13:15:03

标签: javascript angularjs promise

我一直在遇到“然后”没有被等待的行为的麻烦,我理解的原因。但是,我仍然需要解决它。 这是我正在使用的用例。

doWork(family) {
    return doWork1(family)
            .then(resultOfWork1 => doWork2(resultOfWork1));
}

doWork1(family) {
   if (1 === family) {
       return doFamily1();
   } else {
       return doFamily2();
   }
}

doFamily1() {
    return $http(urlToFamily1)
            .then(response => parseFamily1Result(response));
}

parseFamily1Result(response) {
    return parsed response in a family1 way;
}

doFamily2() {
    return $http(urlToFamily2)
            .then(response => parseFamily2Result(response));
}

parseFamily2Result(response) {
   return parsed response in a family2 way;
}

doWork2(resultOfWork1) {
    // use resultOfWork1
}

我正在做的问题是,在doWork2中,resultOfWork1未定义,因为在到达doWork2之前不需要执行“then”承诺。

有没有办法确保“当时”的实现? 或者这种做事方式有问题吗?

2 个答案:

答案 0 :(得分:1)

你错误地链接了承诺。

而不是

doWork(family) {
    return doWork1(family)
            .then(doWork2(resultOfWork1));
}

将其更改为

doWork(family) {
    return doWork1(family)
            .then(function(resultOfWork1){ doWork2(resultOfWork1); });
}

OR

doWork(family) {
    return doWork1(family)
            .then(doWork2);
}

您还需要对以下代码进行类似的更改。

$http(urlToFamily1)
            .then(parseFamily1Result(response));

$http(urlToFamily2)
            .then(parseFamily2Result(response));

答案 1 :(得分:0)

你的问题不是承诺链。这只是因为你的resultOfWork1永远不会被设置,因为你不会在doFamilyX函数中返回任何内容。

doWork(family) {
    return doWork1(family)
            .then(resultOfWork1 => doWork2(resultOfWork1));
}

doWork1(family) {
   if (1 === family) {
       return doFamily1();
   } else {
       return doFamily2();
   }
}

doFamily1() {
    return $http(urlToFamily1)
            .then(response => return parseFamily1Result(response)); //return the result
}

parseFamily1Result(response) {
    return parsed response in a family1 way;
}

doFamily2() {
    return $http(urlToFamily2)
            .then(response => return parseFamily2Result(response)); //return the result
}

parseFamily2Result(response) {
   return parsed response in a family2 way;
}

doWork2(resultOfWork1) {
    // use resultOfWork1
}

现在你的resultOfWork1参数应该设置为parseFamilyXResult返回的值。

Angular promise chaining