简体   繁体   English

在节点js中发出多个请求

[英]Making multiple requests in node js

So I have this overhanging fear this is a question asked many times before but I've searched and every question seem to be tailored to different specific circumstances. 因此,我非常担心这是一个之前多次提出的问题,但是我进行了搜索,每个问题似乎都针对不同的具体情况而量身定制。 If you see it as a duplicate, please flag it and point me in the right direction. 如果您认为它是重复的,请标记它并指向正确的方向。

A general minimal example: 一个一般的最小示例:
I have an array data and want to make an API-call for every element in data , adding things to each element. 我有一个数组data ,并希望进行的API调用中的每一项data ,添加的东西每个元素。 Then I want to get the processed data back. 然后我想取回处理过的数据。

My first attempt (in pseudo:ish code): 我的第一次尝试(使用伪代码:ish代码):

// function that recursively makes the calls
makeCalls(data,i,resolve){
    // base case, we're done
    if(i === data.length){
        return resolve(data);
    }
    const options = {
        url: "http://theapi.com/?name="+data[i].name
    };
    request.post(options,function(error,response,body){
        data[i].item = body.item;
        i++;
        return makeCalls(data,i,resolve);
    }
}

// later on in my code I call the function
new Promise(resolve => makeCalls(data,0,resolve))
    .then(returnedData => console.log("done!"))

Now that solution worked (although it took 264s for 680 calls), but since the calls weren't dependent on each other I thought I could speed it up so I made a loop instead of recursion: 现在该解决方案可以工作了 (尽管680个调用花费了264s的时间),但是由于调用之间并不相互依赖,我认为我可以加快速度,所以我做了一个循环而不是递归:

// function that iteratively makes the calls
makeCalls(data,resolve){
    let j = 0
    const options = {
        url: "http://theapi.com/?name="+data[i].name
    };
    for(let i = 0; i < data.length; i++){
        request.post(options,function(error,response,body){
            data[i].item = body.item;
            j++;
            if(j === data.length)
                return resolve(data);
        }
    }
}

Now 680 calls takes just 56 seconds. 现在680个通话仅需56秒。 Perhaps that's perfectly normal but since I've been winging my code pretty much I'd really like to know if there's an "idiomatic" way of doing this in node? 也许这是完全正常的,但是由于我一直在编写代码,所以我真的很想知道是否在节点中有“惯用的”方法吗? I mean should I really be making the Promise like that and passing the resolve-object into the function? 我的意思是我真的应该像这样做出Promise并将resolve-object传递给函数吗? Is there a "proper" way of making a bunch of API-calls at once? 有没有一种“适当的”方式可以立即进行大量的API调用?


If anyone is curious the data is an array of tracks from the Spotify-API which unfortunately only provide genres on artist level. 如果有人好奇,则data是来自Spotify-API的一系列音轨,不幸的是,这些音轨仅提供艺术家级别的流派。 I need genres on track-level and therefore turn to the LastFM-API which has an endpoint giving me the top-tags of a track. 我需要曲目级别的流派,因此请转到LastFM-API,该API的端点为我提供了曲目的顶部标签。 The only issue is that I need to make this call for every single track :( 唯一的问题是,我需要针对每个音轨进行此调用:(

I would use a wrapper on request to return a promise. 我会在request使用包装器返回承诺。 See the list 查看清单

with that in mind, I would simplify your code using a map function to make every request and update all items, and Promise.all() to wait for all your promises 考虑到这一点,我将使用map函数来简化您的代码,使其发出每个请求并更新所有项目,并Promise.all()等待您的所有承诺

Using request-promise for the example 请求为例

const options = {
        url: "http://theapi.com/?name=" // asumimng you're using an object because there are other options
    };

let promises = data
      .map(element => rp({ ...options, url: options.url + element.name })
                .then(response => element.item = response.item)
      );
return Promise.all(promises).then(() => console.log('done!'));

Any way, what you fixed here mostly is making the code cleaner and declarative. 无论如何,您在此处修复的大部分问题是使代码更简洁,更声明式。 Probably the time is taking you is because all those requests are slow per se. 可能花费您的时间是因为所有这些请求本身都很慢。 Does the API you're using offer you a chance to send multiple ids in one request or something similar? 您使用的API是否为您提供了在一个请求或类似请求中发送多个ID的机会? You might want to do this in one request maybe 您可能想在一个请求中执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM