gpt4 book ai didi

javascript - 循环内的异步调用

转载 作者:行者123 更新时间:2023-11-30 12:03:39 25 4
gpt4 key购买 nike

我有以下代码:

$scope.getEntriesBySpace = function(space, entryIds){
var entriesHolder = [],
errors = [];

if(entryIds && entryIds.length > 0){
angular.forEach(entryIds, function(entryId){
space.cf_space.getEntry(entryId.trim()).catch(function(error) {
console.log('Could not find entry using access token, Error', error);
return error;
}).then(function(response) {
if(response){
entriesHolder.push(data);
}else{
errors.push({"id": entryId, "message": "Entry not found"});
}
});
});
}
};

我是这样调用它的:

$scope.getEntriesBySpace(sourceSpace, entries);

我想在循环内每次调用完成后存储每个响应,并作为响应或错误数组返回。

感谢任何帮助。

方法 getEntry 返回 promise 。

要引用,请参阅此库:https://github.com/contentful/contentful-management.js

谢谢

最佳答案

所以有两种方法可以做到这一点。当您有 promise 时,您通常还会分页 Promise.all 方法,该方法是 promise 实现的一部分。在 Angular 中,你会做 $q.all。

那么你可以这样做:

$q.all(entryIds.map(函数(entryId){
返回 space.cf_space.getEntry(entryId.trim())
}))
.then(函数(条目){
控制台日志(条目)
})

但是,您似乎正在使用内容丰富的 SDK,其中还有一个 getEntries 方法,其中包含 query parameters这允许您在一个请求中一次获得多个条目。这将是最理想的事情,因为它会快得多。

space.cf_space.getEntries({'sys.id[in]': entryIds.join(',')})
.then(函数(条目){
控制台日志(条目)
})

关于javascript - 循环内的异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35943746/

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