简体   繁体   中英

Push items in array asynchronously

I want to push an object into array that one of the field is value need to get from async function

function loadContentAsync(url) {
    var deferred = Q.defer();
    request(url, function (err, res, html) {
        if (!err) {
            deffered.resolve(html);
        }
    });
    return deffered.promise;
}

var aList = $('#mCSB_5_container ul').find('a');
console.log(c);

var list = [];
aList.each(function (i, elem) {
    var html = loadContentAsync(this.attribs.href);
    list.push({
        title: $(this).text(),
        url: this.attribs.href,
        content: html
    });
});

But when I run this code, because loadContentAsync function doesn't return value synchronously, the html field will be null.

How can I this field asynchronously?

You need to wait for the promises to be resolved. In order to maintain the correct order of the elements, you should use Q.all() to accumulate the results of all the promises:

function loadContentAsync(url) {
    var defer = Q.defer();
    request(url, function (err, res, html) {
        if (err) {
            defer.reject(err);
        }
        else {
            defer.resolve(html);
        }
    });
    return defer.promise;
}

var aList = $('#mCSB_5_container ul').find('a');
console.log(c);

var promises = aList.map(function (i, elem) {
    return loadContentAsync(this.attribs.href);
}).get();

var list = [];
Q.all(promises).then(function (htmlList) {
    htmlList.forEach(function (html) {
        list.push({
            title: $(this).text(),
            url: this.attribs.href,
            content: html
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM