gpt4 book ai didi

javascript - 需要帮助解决嵌套的 Promise,Promise 没有得到解决

转载 作者:行者123 更新时间:2023-12-03 06:01:16 24 4
gpt4 key购买 nike

我设计了一个服务,它接受一些参数,然后循环输入数组,找出哪个项目是空的,然后将它们添加到数组中,然后在 $q.all 解析后,它应该给我空项目的数组.

输入是项目数组

function getElements(inputs) {
var elements= [],
promise, whenPromise,
promises = [],
mainPromise = $q.defer();
if (inputs.length === 0) {
mainPromise.resolve(elements);
return mainPromise.promise;
}

angular.forEach(inputs, function (input) {
promise = getPromises(input);
whenPromise = $q.resolve(promise).then(function (response) {
$timeout(function() {
if (response.isEmpty) {
**//perform action with the response.data;**
}
});
}, function () {

});

promises.push(whenPromise);
});


$q.all(promises).finally(function () {
mainPromise.resolve(outdatedEntities);

});

return mainPromise.promise;
}

function getPromises(input) {
var deferred = $q.defer();

someSerivce.getItemDetails(input.Id).then(function (value) {
if (value === null) {
$timeout(function () {
deferred.resolve({data: input, isEmpty: true});
});

} else {
//have item locally, but need to see if it's current
input.isEmpty().then(function (isEmpty) {
$timeout(function () {
deferred.resolve({data: input, isEmpty: isEmpty});
});
}, function (error) {
deferred.reject(error);
});
}

});

return deferred.promise;
}

现在,问题是 $q.all 从未得到解决。尽管所有内部 promise 都得到了解决。

最佳答案

这应该有效:

function getElements(inputs) {
var elements = [],
promise, whenPromise,
promises = [],
mainPromise = $q.defer();
if (inputs.length === 0) {
mainPromise.resolve(elements);
return mainPromise.promise;
}

angular.forEach(inputs, function (input) {
promise = getPromises(input);
whenPromise = promise.then(function (response) {

if (response.isEmpty) {
* *//perform action with the response.data;**
}

}, function () {

});

promises.push(whenPromise);
});


return $q.all(promises).finally(function () {
return outdatedEntities;
});
}

function getPromises(input) {
return someSerivce.getItemDetails(input.Id).then(function (value) {
if (value === null) {
return {data: input, isEmpty: true};
} else {
//have item locally, but need to see if it's current
return input.isEmpty().then(function (isEmpty) {
return {data: input, isEmpty: isEmpty};
}, function (error) {
return error;
});
}
});
}

关于javascript - 需要帮助解决嵌套的 Promise,Promise 没有得到解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39743532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com