数据没有推入数组nodejs

data not pushing in array nodejs

我有一个函数,它接受一个 url 数组并使用 npm 包 'read-titles' 获取那些 url 的标题。它成功 console.log 标题但没有将其推入 array.The 数组打印为空。密码是

function getTitleArray(addresses) {
    var titles = [];
    if (addresses.length > 1) {
        addresses.forEach((urls) => {

            console.log(urls.search('http'));
            if (urls.search('http://') == -1) {
                urls = 'http://' + urls;
            }

            readTitle(urls).then((title) => {
                titles.push(title);
                console.log(title);
            }, (err) => {
                res.status(400).send(err);
            });

        });
    }
    console.log('Titles are: ' + titles);
    return titles;
}

由于 readTitle 是异步的,因此返回空数组作为响应,这里使用 Javascript 回调修改了代码片段。试试这个。

function getTitleArray(addresses, callback) {
    var titles = [];
    if (addresses.length > 1) {
        addresses.forEach((urls, index) => {

            console.log(urls.search('http'));
            if (urls.search('http://') == -1) {
                urls = 'http://' + urls;
            }

            readTitle(urls).then((title) => {
                titles.push(title);
                console.log(title);
                if((addresses.length - 1) === index) {
                    callback(null, titles);
                }               
            }, (err) => {
                callback(err)
            });
        });
    }
}

getTitleArray([], (err, titles) => {
    if(err) {
        res.status(400).send(err);
    } else {
        console.log("Title :", titles);
    }   
})

正如@Mark_M所说,你有一个异步代码,所以当所有readTitle调用结束时,你必须制作一个回调系统来访问标题。

这是您可以使用的递归方式:

function getTitleArray(addresses, callback) {

    var titles = [];
    if (addresses.length > 1) {

        let syncCallReadTile = function (it = 0, callback) {
            let url = addresses[it];
            if (url.indexOf('http://') == -1) {
                url = 'http://' + url;
            }
            readTitle(url).then((title) => {
                titles.push(title);
                it++;
                if (it == addresses.length) {
                    callback(null, titles);
                }
                else {
                    syncCallReadTile(it, callback);
                }
            }, callback);
        };

        syncCallReadTile(0, callback);

    }
}

getTitleArray([], (err, titles) => {
    if (err) {
        res.status(400).send(err);
    }
    else {
        console.log("Title :", titles);
    }   
})