1

抱歉,如果这是一个愚蠢的问题,但我将如何将项目添加到列表中?所以我得到的是一个循环,它基本上贯穿并尝试将所有 url 从 web scraper转换为 tinyurls 。它仍然为 images_short 生成一个空列表。我对nodejs的语法不是很熟悉。这是一段代码,我在 images_long 列表中放入了一些数据:

const TinyURL = require('tinyurl');

var images_long = ['https://hypebeast.imgix.net/http%3A%2F%2Fhypebeast.com%2Fimage%2F2017%2F06%2Fadidas-skateboarding-lucas-premiere-adv-primeknit-khaki-0.jpg?fit=max&fm=pjpg&h=344&ixlib=php-1.1.0&q=90&w=516&s=728297932403d74d2ac1afa5ecdfa97d', 'https://hypebeast.imgix.net/http%3A%2F%2Fhypebeast.com%2Fimage%2F2017%2F06%2Fadidas-nmd-r1-stlt-triple-black-first-look-0.jpg?fit=max&fm=pjpg&h=344&ixlib=php-1.1.0&q=90&w=516&s=918752eba81826e4398950efc69a5141'];
var images_short = [];

for (i = 0; i < 2; i++) {
    TinyURL.shorten(images_long[i], function(res) {
        images_short.push(res[i]);
    });
}

当我更改为时,我仍然得到一个空images_short.push(res[i]);列表images_short.push(res);

4

2 回答 2

0

res是一个字符串,所以就images_short.push(res);可以了。此外,您应该针对要索引的变量的长度进行迭代,并且应该使用var您的索引变量 ( i):

const TinyURL = require('tinyurl');

var images_long = [
    'https://hypebeast.imgix.net/http%3A%2F%2Fhypebeast.com%2Fimage%2F2017%2F06%2Fadidas-skateboarding-lucas-premiere-adv-primeknit-khaki-0.jpg?fit=max&fm=pjpg&h=344&ixlib=php-1.1.0&q=90&w=516&s=728297932403d74d2ac1afa5ecdfa97d',
    'https://hypebeast.imgix.net/http%3A%2F%2Fhypebeast.com%2Fimage%2F2017%2F06%2Fadidas-nmd-r1-stlt-triple-black-first-look-0.jpg?fit=max&fm=pjpg&h=344&ixlib=php-1.1.0&q=90&w=516&s=918752eba81826e4398950efc69a5141'];
var images_short = [];

for (var i = 0; i < images_long.length; i++) {
    TinyURL.shorten(images_long[i], function(res) {
        images_short.push(res);
    });
}
于 2017-06-29T01:41:49.570 回答
0

tinyurl 库是异步的。

console.log(images_short)如果我们使用本机地图,如果我们尝试直到数组中的所有链接都被缩短,则不会返回结果回调。

但是,我们可以使用async并专门用于async.map返回结果,如下例所示。

const TinyURL = require('tinyurl');
const async = require('async');

var images_long = [
    'https://hypebeast.imgix.net/http%3A%2F%2Fhypebeast.com%2Fimage%2F2017%2F06%2Fadidas-skateboarding-lucas-premiere-adv-primeknit-khaki-0.jpg?fit=max&fm=pjpg&h=344&ixlib=php-1.1.0&q=90&w=516&s=728297932403d74d2ac1afa5ecdfa97d',
    'https://hypebeast.imgix.net/http%3A%2F%2Fhypebeast.com%2Fimage%2F2017%2F06%2Fadidas-nmd-r1-stlt-triple-black-first-look-0.jpg?fit=max&fm=pjpg&h=344&ixlib=php-1.1.0&q=90&w=516&s=918752eba81826e4398950efc69a5141'];

function shorten(item, cb) {
  TinyURL.shorten(item, function(res) {
    cb(null, res);
  });
}

async.map(images_long, shorten, (err, results) => {
  console.log(results);
});

images_short如果您想保持一致性,我们可以分配。

于 2017-06-29T03:19:35.597 回答