异步推送数组中的项目

时间:2015-08-21 11:56:44

标签: javascript node.js asynchronous q

我想将一个对象推入数组,其中一个字段值需要从异步函数

获取
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
    });
});

但是当我运行此代码时,因为loadContentAsync函数没有同步返回值,所以html字段将为null。

我该怎么异步这个字段?

1 个答案:

答案 0 :(得分:1)

您需要等待承诺得到解决。为了保持元素的正确顺序,您应该使用Q.all()来累积所有承诺的结果:

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
        });
    });
});