在 AngularJS 中使用 angular.forEach 实现异步 await

Implement async await using angular.forEach in AngularJS

提问人:Pushpinder Bharaj 提问时间:11/27/2019 最后编辑:georgeawgPushpinder Bharaj 更新时间:11/29/2019 访问量:756

问:

我正在尝试使用 api 保存所选项目列表的标签。在 api 中,我只为第一个选定的项目存储一次标签,其余的我不存储项目,而是将条目创建为共享。 问题是:第一个选定的项目命中了 api,在存储数据之前,其他选定的项目也被命中,我无法提供共享引用,因为数据尚未存储。

我尝试过的事情——

这是我的控制器:

let selectedQstCount = $scope.selectedQuestion.length;
for (i = 0; i < selectedQstCount; i++) {
    var params = {
        "jsonString": callbackData,
        "questionNo": $scope.Questionlst.find(a => a.QuestionId == $scope.selectedQuestion[i].id).QuestionNo,
        "projectName": $scope.ProjectName,
        "projectId": $scope.ProjectId,
        "questionId": $scope.selectedQuestion[i].id,
        "newCodeFrame": ($scope.attachCodeFrame == "No" ? "FALSE" : "TRUE"),
        "sharedQstId": $scope.sharedQstId,
        "groupName": $scope.groupName
    }
    var defer = $q.defer();
    CodeFrameJsonfactory.CodeFrameUpload(params, function (data) {
        //success
        $q.resolve(data);
    }, function (callbackData) {
        //error
        inform.clear();
        inform.add(callbackData.Message, { ttl: -1, type: 'danger' });
    });
    return defer.promise;
}

这是我的工厂:

CodeFrameUpload: function (params, successCallback, errorCallback) {
    var deferred = $q.defer();
    $http({
        method: 'POST',
        url: APIUrls.getUrl("uploadCodeFrame"),
        data: params,
        headers: {
            'Content-Type': 'application/json'
        },
        cache: false
    }).success(function (data) {
        deferred.resolve(data);
        successCallback(data);
    }).error(function (data) {
        deferred.reject(data);
        errorCallback(data);
    });
    return deferred.promise;
},

我也尝试过将angular.forEach与deffered一起使用。

我想要实现的是,在CodeFrameUpload功能完成之前,我不想再次击中它。

angularjs 异步 async-await 延迟

评论

0赞 georgeawg 11/27/2019
该方法已从 AngularJS 框架中删除.success

答:

0赞 georgeawg 11/27/2019 #1

返回数据承诺:

CodeFrameUpload: function (params) {
    return $http({
        method: 'POST',
        url: APIUrls.getUrl("uploadCodeFrame"),
        data: params,
        headers: {
            'Content-Type': 'application/json'
        },
        cache: false
    }).then(function(response) {
        return response.data;
    });
},

映射返回的 promises:

var promiseArr = $scope.selectedQuestion.map(question => {
    var params = {
        "jsonString": callbackData,
        "questionNo": $scope.Questionlst.find(a => a.QuestionId == question.id).QuestionNo,
        "projectName": $scope.ProjectName,
        "projectId": $scope.ProjectId,
        "questionId": question.id,
        "newCodeFrame": ($scope.attachCodeFrame == "No" ? "FALSE" : "TRUE"),
        "sharedQstId": $scope.sharedQstId,
        "groupName": $scope.groupName
    }
    return CodeFrameJsonfactory.CodeFrameUpload(params);
});

用:$q.all

$q.all(promiseArr).then(function(dataArr) {
    console.log(dataArr);
}).catch(function(errResponse) {
    console.log(errResponse);
});

$q.all返回一个 promise,该 promise 将使用值的数组/哈希进行解析,每个值对应于 promise 数组/hash 中同一索引/键处的 promise。如果任何 promise 以拒绝方式解析,则此结果 promise 将以相同的拒绝值被拒绝。

有关更多信息,请参阅 。


更新

上面的示例并行执行 HTTP 请求。

要按顺序链接 promise:

var paramsArr = $scope.selectedQuestion.map(question => ({
        "jsonString": callbackData,
        "questionNo": $scope.Questionlst.find(a => a.QuestionId == question.id).QuestionNo,
        "projectName": $scope.ProjectName,
        "projectId": $scope.ProjectId,
        "questionId": question.id,
        "newCodeFrame": ($scope.attachCodeFrame == "No" ? "FALSE" : "TRUE"),
        "sharedQstId": $scope.sharedQstId,
        "groupName": $scope.groupName
}));

var sequentialPromise = paramsArr.reduce( (promise, paramsObj) => {
    promise.then(function(dataArr) {
        var singlePromise = CodeFrameJsonfactory.CodeFrameUpload(paramsObj);
        return $q.all([...dataArr, singlePromise]);
    },
    $q.when([])
);

sequentialPromise.then(function(dataArr) {
    console.log(dataArr);
});

评论

0赞 Pushpinder Bharaj 11/28/2019
我认为.map .forEach不是同步调用ajax的正确方法。它一下子击中了 api。必须有其他方法。
0赞 georgeawg 11/29/2019
更新了答案,以显示链接顺序承诺的示例。