[英]chain promises in map loop
我知道有很多關於這個主題的帖子,但我無法弄清楚。 我是所有這些承諾的新手,但我有一個需要解決的特定問題。 在下面的代碼中,我循環遍歷一個數組“fnFoes”,並在這個 fnFoes 中通過另一個數組“avatar”。 對於 avatar 中的每個元素,一個來自 indexedDB 的 svg-Code 被加載並附加到 html。 我的問題是:我希望此函數在完成該函數並繼續執行下一個函數之前完全加載並附加所有 svg。
我試圖將整個函數包裝成一個promis,但在加載所有svg之前它仍然繼續。 我認為這與 indexedDB 有關,但老實說,我只是不明白。
經過 2 天的帖子閱讀和反復試驗,非常感謝任何幫助!! 謝謝弗里茨
$.map(fnFoes, function(i,obj){
console.log(obj);
console.log('loadAllAvatars: checking foe: ' + obj);
if (!(obj in foes) || fnFoes[obj].avatar != foes[obj].avatar || document.getElementById(obj) === null){ // compare avatar information of both variables. if changed, render new
console.log('loadAllAvatars: foe '+ obj +' will be rendered');
foeRenderIds.push(obj); // push foe id in list
if (obj in foes) {
foes[obj].avatar = fnFoes[obj].avatar; // change avatar items in foes;
}
var avatar = fnFoes[obj].avatar.split(','); // split avatar string in array
console.log(avatar);
console.log(fnFoes[obj]);
if (document.getElementById('#'+obj)){ // if foe div already exists in avatarDoubles, just delete it
$('#'+obj).html(); // delete old avatar from doubles
} else {
var html ='<div id="foe' + obj + '"></div>'; // if avatar doesn't exist, create it in avatarDoubles
$('#avatarDoubles').append(html);
}
//render avatar
if (typeof avatar !== 'undefined' && avatar.length > 1) {
$.map(avatar, function(j,key){
console.log(avatar[key]);
var name = avatar[key];
db.svgs.get(name).then(function(obj2){
var html = "<div class='" + obj2.category + "' data-name='" + obj2.name + "' data-category='" + obj2.category + "'>" + obj2.svg + "</div>";
$('#foe' + obj).append(html);
console.log(obj2.name);
});
});
}
} else {
console.log('loadAllAvatars: foe '+ obj +' already exists');
}
});
我很難理解你的代碼,但你可能想要這樣的東西:
function connect() {
return new Promise(function(resolve, reject){
var request = indexedDB.open();
request.onsuccess = () => resolve(request.result);
});
}
function dothings(db, things) {
var promises = [];
for(var thing of things) {
var promise = dothing(db, thing);
promises.push(promise);
}
return Promise.all(promises);
}
function dothing(db, thing) {
return new Promise(function(resolve, reject) {
var tx = db.transaction('svgs');
var store = tx.objectStore('svgs');
var request = store.get(thing);
request.onsuccess = () => resolve(request.result);
});
}
function foo() {
var things = getthings();
connect().then(function(db) {
return dothings(db, things);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.