【问题标题】:How can I use the results of data produced by the ".each" method?如何使用“.each”方法产生的数据结果?
【发布时间】:2017-07-17 22:17:04
【问题描述】:

我使用Dexie.js(一个IndexedDb wapper)。

我尝试过像这样生成 HTML:

function getList(where){
    var html = [];
    if($.isEmptyObject(where)) return;
    db.modules.where(where).each(function(item){
        html.push('<div class="module-item">');
        html.push('<div class="module-item-pic"><img src="' + item.modu_pic + '" class="img-fluid" /></div>');
        ....
        html.push('</div>')
        html.push('</div>');
    })
    console.log(html.join(''));
}

但是上面的代码什么也没输出。

但是,当我将 console.log(html.join('')) 放入到 .each 的回调中时,我得到了一个输出:

function getList(where){
    var html = [];
    if($.isEmptyObject(where)) return;
    db.modules.where(where).each(function(item){
        html.push('<div class="module-item">');
        html.push('<div class="module-item-pic"><img src="' + item.modu_pic + '" class="img-fluid" /></div>');
        ....
        html.push('</div>')
        html.push('</div>');
console.log(html.join(''));
    })

}

为什么我的第一个代码 sn-p 没有显示任何输出?

【问题讨论】:

    标签: scope dexie


    【解决方案1】:

    请记住,Dexie 操作通常是异步的。问题是您的第一个代码 sn-p 在完成任何异步操作之前立即执行console.log(html.join(''))

    您需要使用.each 返回的promise 等到所有迭代完成后再尝试输出到控制台:

    function getList(where){
        var html = [];
        if($.isEmptyObject(where)) return;
        db.modules.where(where).each(function(item){
            html.push('<div class="module-item">');
            html.push('<div class="module-item-pic"><img src="' + item.modu_pic + '" class="img-fluid" /></div>');
            ....
            html.push('</div>')
            html.push('</div>');
        }).then(function () {
          console.log(html.join(''));
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2018-08-07
      • 2018-12-17
      • 2018-09-27
      • 2020-11-14
      相关资源
      最近更新 更多