NodeJS + TinyURL - 将项目添加到列表

NodeJS + TinyURL - adding items to a list

抱歉,如果这是一个愚蠢的问题,但我该如何将项目添加到列表中?所以我得到的是一个循环,它基本上贯穿并尝试将所有 url 从网络 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);

时,我仍然得到一个空列表

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

tinyurl 库是异步的。

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

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

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