javascript - 检查所有请求是否已完成

标签 javascript node.js asynchronous request-promise

我目前正在开发一个异步获取多个 URI 的抓取工具。 我的问题是,我想等待所有响应得到处理,但我不知道如何找出每个响应的处理时间。

最后一条日志显示“完成!”甚至在响应返回之前就运行。

感谢您的帮助 克萨维尔:)

const rp = require('request-promise');
const cheerio = require('cheerio');

//The function
function getData(arr) {


    // Using loop to fetch every adress
    for (let i = 0; i < arr.length; i++) {



        //Setting my options
    let opt = {
        method: 'GET',
        //Inserting index into url to get different site every loop
        uri: `https://example.de/${i}`,
        headers: {
            Referer: 'example.de',
        },
        resolveWithFullResponse: true,
        //Loading jquery/cherrio
        transform: function (body) {
            return cheerio.load(body);
        }
    };

    //running the request
    rp(opt)
    .then(($) => {
        console.log('Success fetching Data of : ' + arr[i])
        console.log('Now formatting!')


        //formatting my data ...


    })

    .catch((err => {
        //err handling
        console.error(err.message)
        console.info(`Retrying in ${errDelay / 1000}sec`)
        setTimeout(() => {
            rp(opt)
        }, errDelay);
    }))



}

//This should run after every request is formatted but currently it runs before the requests are done BUT IT DOESN'T
console.log('Done!')


}

getData()``` 

最佳答案

Promise.all就是你想要的。

Promise.all(arr.map((_,i)=>{
    //Setting my options
    let opt = {
        method: 'GET',
        //Inserting index into url to get different site every loop
        uri: `https://example.de/${i}`,
        headers: {
            Referer: 'example.de',
        },
        resolveWithFullResponse: true,
        //Loading jquery/cherrio
        transform: function (body) {
            return cheerio.load(body);
        }
    };

    //running the request
    return rp(opt)
    .then(($) => {
        console.log('Success fetching Data of : ' + arr[i])
        console.log('Now formatting!')


        //formatting my data ...

    })
    .catch((err => {
        //err handling
        console.error(err.message)
        console.info(`Retrying in ${errDelay / 1000}sec`)
        setTimeout(() => {
            rp(opt)
        }, errDelay);
    }))
}).then(()=> console.log('done'))

关于javascript - 检查所有请求是否已完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59488057/

相关文章:

javascript - 无法弄清楚为什么它不起作用。 javascript调用数据键

javascript - 使用 ReactJS 中的 AceEditor 了解光标在文本中的位置

javascript - Jquery 和 Css 以及数学 : dots in a circle to converge in one point

javascript - 我可以说 Nodejs 就像 JVM 但是是针对 JavaScript 的吗?

javascript - 如何在 couchdb 中获取表的数据

javascript - 引用错误: _spPageContextInfo is not defined

mysql - Nodejs mysql如何处理超时和握手不活动超时

flutter - Flutter中OnChanged函数执行后调用Future

c++ - 当 TCP TX 缓冲区填满时,boost::asio 会发生什么?

angular - 如何使用异步管道遍历对象中的数组