$q - 控制函数执行的顺序

$q - Control order of function execution

本文关键字:执行 顺序 函数 控制      更新时间:2023-09-26

我是AngularJS的新手,我正在尝试构建一个带有承诺的函数,因此只有在前一个函数完成后才能运行。

我有一系列发票。 除客户参考编号外,每张发票都不存储客户信息。使用客户参考编号,我想使用参考编号查询我的 API 以获取客户名称。

    $scope.invoices.forEach(function(invoice) {
        var defer = $q.defer();
        defer.promise.then(function(invoice) {
            var customer_id = invoice[$rootScope.data]["Id"][0].match(/'d+/)[0];
            $http.post('/customers', customer_id).success(function(response) {
                console.log("Response is: " + response);
                return response;
            });
        }).then(function(result) {
            invoice.customer_name = result;
            console.log("The final result is: " + result);
            return invoice.customer_name;
        });
        defer.resolve(invoice);
    });

注意:目前,我的 API 仅返回给定的参考编号。

在我的控制台中,我看到以下输出:

(10) The final result is: undefined
Response is: 235
Response is: 239
Response is: 234
Response is: 238
Response is: 237
Response is: 236
Response is: 233
Response is: 232
Response is: 231
Response is: 230

如何确保第二个then仅在第一个之后运行?

在这种情况下,典型的方法是将$q.all与 promise 数组一起使用。使用Array.prototype.map方法组合这样的数组很方便:

var promises = $scope.invoices.map(function(invoice) {
    var customer_id = invoice[$rootScope.data]["Id"][0].match(/'d+/)[0];
    return $http.post('/customers', customer_id).then(function(result) {
        invoice.customer_name = result.data;
        console.log("The final result is: " + result);
        return invoice.customer_name;
    });
});
$q.all(promises).then(function(responses) {
    // console.log(responses);
});

$q.all承诺解决时,您应该按正确的顺序获得一组客户名称。