??
Проблема в функции getUrlData
. api.space.getEntries
возвращает обещание, которое вы правильно используете с then
. Дело в том, что с обещаниями они асинхронны (как и многие другие в javascript).
То есть вы инициализируете urlDataArray
и делаете вызов содержательному. И вы заполняете этот массив, когда вызов возвращается. Дело в том, что getUrlData
уже вернул пустой массив.
function getUrlData(){
var urlDataArray = [];
api.space.getEntries()
.then(function (entries) {
// this part is executed async
entries.items.forEach(function (entry) {
if(entry.fields.url){
var urlData = entry.fields.url.en
urlDataArray.push(urlData);
}
})
})
return urlDataArray;
};
Лучший способ приблизиться к этому ИМО, чтобы изменить getUrlData
и вернуть обещание.
function getUrlData() {
// return this promise
return api.space.getEntries()
.then(function(entries) {
// there is no need for another array
// you can use map to grab the data you need
return entries.items.map(function(item) {
// map all the entries to the url strings
return item.fields.url.en;
})
})
}
getUrlData()
// only execute this when the data is there
.then(function(urls) { console.log(urls); })
Ваш код выполняется в UI-расширении, но я также быстро изменил ваш код в codepen . Он использует Contentful CDA, но принципы остаются теми же.
Надеюсь, это поможет. :)