首页 > Promise的用法问题

Promise的用法问题

问题

现在想用Promise让所有图片加载完之后执行其他逻辑
看了很多资料会简单使用Promise了,但是在循环里就蒙了。。
Promise.all()的参数该怎么弄呢?

$.each(data, function (i, n) {

    //insert Name
    wall.insert(n.id, n.nickname, 'name');

    //Photo and Avatar load
    wall.loadImg(n.photo, function () {

        wall.loadImg(n.avatar, function () {
            wall.insert(n.id, n.avatar, 'avatar');
            wall.insert(n.id, n.photo, 'photo');

            wallData.showKey.push(n.id);
           
        });
    });
});

wall.loadImg = function (url, cb, er) {
    new Promise((resolve, reject) => { 
        var img = new Image();
        img.src = url;
        if(img.complete){
            cb()
            resolve()
        }else {
            img.onload = function(){ resolve() };
            img.onerror = er;
        }
    }); 
};

从你的代码里,没看出来哪里是Promise,你应该贴出和Promise相关的代码。至于怎么resolve多个Promise,我想@nealnote 说的很清楚了

你的用法仍然是callback,不是Promise风格,我稍微改了下:

var promises = $.map(data, function(i, n) {

    //insert Name
    wall.insert(n.id, n.nickname, 'name');

    //Photo and Avatar load
    return wall.loadImg(n.photo)
        .then(function() {
            return wall.loadImg(n.avatar);
        })
        .then(function() {
            wall.insert(n.id, n.avatar, 'avatar');
            wall.insert(n.id, n.photo, 'photo');

            wallData.showKey.push(n.id);
        });
});

wall.loadImg = function(url) {
    return new Promise((resolve, reject) => {
        var img = new Image();
        img.src = url;
        if (img.complete) {
            return resolve();
        }
        img.onload = resolve;
        img.onerror = reject;
    });
};

Promise.all(promises)
    .then(function() {
        console.log('all have been done!!!!');
    });

Promise.all()

Promise.all(iterable) 方法返回一个promise,该promise会等iterable参数内的所有promise都被resolve后被resolve,或以第一个promise被reject的原因而reject 。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

【热门文章】
【热门文章】