【问题标题】:Incremental loading of images with promises使用承诺增量加载图像
【发布时间】:2016-01-04 09:05:07
【问题描述】:

我正在尝试加载相同的图像,但分辨率不同,首先是 1.png,然后是 2.png,然后是 3.png,在 promise 的帮助下,但是当我运行代码时,它只加载3.png图像,我做错了什么?

function loadi(srce){
        if(srce!='3.png'){
        $img1.attr('src',srce).on('load',function(){

            return loadImag();
        });
        }
        else{
            $img1.attr('src',srce).on('load',function(){
                console.log("Load successful");
            });
        }
    }
    function loadImag(){
        return new Promise(function(fulfill,reject){
            fulfill();
        }); 
    }
    loadImag()
            .then(loadi('1.png'),null)
            .then(loadi('2.png'),null)
            .then(loadi('3.png'),null);

第一个建议后的新代码,仍然面临同样的问题,只有一个图像被加载,如在 chrome 开发工具中看到的那样

function loadi(srce){

            return loadImage(srce);

    }

    function loadImage(src) {
        return new Promise(function(resolve, reject) {
            $img1.attr('src',src).on('load',function(error){

                     resolve(); 
            });
// Run image loading logic here
// Call resolve() when loading complete, or reject() when fails.
        });
    }

    loadImage('1.png')
            .then(loadi('2.png'))
            .then(loadi('3.png'))
            .then(function() { 
                console.log('Load successful!'); 
            }) // Not in loadImage().
            .catch(function(err) { 
                        console.log("Error");/* Handle potential errors */
});

【问题讨论】:

    标签: javascript jquery promise rsvp-promise


    【解决方案1】:

    您的代码几乎没有问题:

    • loadi 不返回 Promise。从回调返回没有按预期工作。
    • loadImag基本可以换成Promise.resolve()
    • .then() 期待一个函数,你正在传递函数的结果。

    您的代码应如下所示:

    function loadImage(src) {
      return new Promise(function(resolve, reject) {
        // Run image loading logic here
        // Call resolve() when loading complete, or reject() when fails.
      )};
    }
    
    loadImage('1.png')
      .then(function() { return loadImage('2.png'); })
      .then(function() { return loadImage('3.png'); })
      .then(function() { console.log('Load successful!'); }) // Not in loadImage().
      .catch(function(err) { /* Handle potential errors */ });
    

    【讨论】:

    • 我试过这样做,但仍然面临同样的问题
    • @AnkitParasha:您的代码与我的示例不同。
    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 2020-10-22
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2011-09-24
    • 2020-01-23
    • 1970-01-01
    相关资源
    最近更新 更多