【问题标题】:Requesting URL's one by one一个个请求 URL
【发布时间】:2021-11-01 17:13:40
【问题描述】:

我正在尝试使用“请求”从许多 URL 中获取一些数据,但我无法一次处理一个 url。

我试图理解 async/promises 以使其工作,但没有成功。反复试验没有奏效。

我见过使用不同模块的其他方法,但这需要重写我的大部分代码,我相信有一种更简单的方法可以使其适应我当前的代码。

这是代码的最小化版本:

const request = require('request');
const fs = require('fs');
const prod = fs.readFileSync('prod.txt', "utf8");
const prodid = prod.split("|");
var i;
var summary=[];


for (i=0;i<prodid.length;i++){
request('https://www.api.example.com/id='+prodid[i], { json: true }, (err, res, body) => {
  if (err) { return console.log(err); }
if (body == 'NULL') {
   console.log("Page " + i + " out of " + prodid.length + " is NULL!");
} else {
summary.push(body.items[0].Name);
summary.push(body.items[0].ISOnr);
summary.push(body.items[0].GTIN);
console.log("Page " + i + " out of " + prodid.length + " is done!");
fs.appendFileSync('data.txt',JSON.stringify(summary));
}

});
}

上面的例子没有涉及异步/承诺,只是循环内的请求。

据我所见,当我得到结果时,没有特定的顺序(可能是先完成的顺序)。

在控制台中,我总是在 500 页中看到第 500 页,而不是 1/500、2/500 等。

我想要实现的是,按照 URL 的顺序发出每个请求(最好在它们之间有 1000 毫秒的延迟)

【问题讨论】:

  • 如果它们是独立的请求,而您需要完成所有请求,为什么不简单地在最后关联一下?

标签: node.js node-request


【解决方案1】:

您可以承诺您的请求:

for (i = 0; i < prodid.length; i++) {
    const result = await new Promise((resolve, reject) =>
        request(
            'https://www.api.example.com/id=' + prodid[i],
            { json: true },
            (err, res, body) => {
                if (err) {
                    reject(err);
                }
                if (body == 'NULL') {
                    console.log('Page ' + i + ' out of ' + prodid.length + ' is NULL!');
                } else {
                    resolve(body);
                }
            }
        )
    );
    if (result) {
        summary.push(result.items[0].Name);
        summary.push(result.items[0].ISOnr);
        summary.push(result.items[0].GTIN);
        console.log('Page ' + i + ' out of ' + prodid.length + ' is done!');
        fs.appendFileSync('data.txt', JSON.stringify(summary));
    }
}

【讨论】:

    猜你喜欢
    • 2013-09-29
    • 2017-11-25
    • 2020-09-28
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    相关资源
    最近更新 更多