JavaScript/Promise-定义承诺链接之间的超时
我使用ChereIOJS来废弃一个站点,我需要在几个url参数上发出大量请求 最小代码:JavaScript/Promise-定义承诺链接之间的超时,javascript,es6-promise,Javascript,Es6 Promise,我使用ChereIOJS来废弃一个站点,我需要在几个url参数上发出大量请求 最小代码: const rp = require('request-promise'); const cheerio = require('cheerio'); [1, 2, 3].forEach(element => { url = `https://stackoverflow.com/q=${element}` rp(url) .then((html) => { // Lo
const rp = require('request-promise');
const cheerio = require('cheerio');
[1, 2, 3].forEach(element => {
url = `https://stackoverflow.com/q=${element}`
rp(url)
.then((html) => {
// Logic code
})
})
我想在每个请求之间设置一个超时,如何定义它?如果要使用
forEach
语句,请使用我的第一个代码。如果这对您不重要,请参阅我的第二个(更简单)工作示例,它基于@JFord的答案
注意:代码已修复,可以正常工作
forEach
示例
const rp=require('request-promise'))
const cheerio=require('cheerio')
功能睡眠(ms){
返回新承诺(解析=>setTimeout(解析,毫秒))
}
异步函数forEachAsync(arr,fn){
对于(变量i=0;i{
等待睡眠(2000年)
console.log('2000秒'
变量url=`https://stackoverflow.com/questions/${element}`
等待rp(url)
。然后(html=>{
console.log(html)
})
.catch(函数(e){
console.log(e.message)/“哦,不!”
})
})
}
fetchURL()
列表项的示例
这是一个工作示例,基于@JFord的答案,但另外处理错误
const rp = require('request-promise')
const cheerio = require('cheerio')
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function fetchUrls(list) {
for (const item of list) {
const html = await rp(`https://stackoverflow.com/q=${item}`).catch(function(e) {
console.log(e.message) // There's an error
})
console.log("html: " + html)
await sleep(2000);
}
}
fetchUrls([1,2,3])
您可以使用forEach
的索引参数作为超时延迟的乘数
const delay = 1000
[1, 2, 3].forEach((element, i) => {
url = `https://stackoverflow.com/q=${element}`
setTimeout(() => {
rp(url)
.then((html) => {
// Logic code
})
}, i * delay);
})
目前,所有请求基本上都是并行的。在添加它们之间的延迟之前,必须按顺序执行它们。你可以通过链接承诺来实现这一点。使用很容易做到这一点。减少:
const rp=require('request-promise');
const cheerio=需要(“cheerio”);
[1,2,3]。减少((p,元素)=>{
url=`https://stackoverflow.com/q=${element}`
返回p
.然后(()=>rp(url))
。然后((html)=>{
//逻辑码
});
},Promise.resolve())
这将构建一个相当于
rp(url1)
.then(html => ...)
.then(() => rp(url1))
.then(html => ...)
.then(() => rp(url2))
.then(html => ...)
为了添加延迟,我们定义了一个函数,该函数返回一个函数,该函数通过setTimeout
返回x毫秒后解析的承诺:
函数等待(x){
return()=>newpromise(resolve=>setTimeout(resolve,x));
}
现在我们可以将其添加到我们的链中(我在这里用一些可运行的东西替换rp
):
函数等待(x){
return()=>newpromise(resolve=>setTimeout(resolve,x));
}
[1,2,3]。减少((p,元素)=>{
常量url=`https://stackoverflow.com/q=${element}`
返回p
.然后(()=>Promise.resolve(url))
。然后((html)=>{
log(`Fetched${html}`);
})
.然后(等等(2000));
},Promise.resolve())
我认为最可读的方法是使用异步函数和Promise
功能睡眠(毫秒){
返回新承诺(resolve=>setTimeout(resolve,millis));
}
异步函数进程(列表){
用于(列表中的常量项){
const html=wait rp(`https://stackoverflow.com/q=${item}`);
…做事
等待睡眠(1000);
}
}
这将在3秒后立即执行所有请求。@FelixKling感谢您指出我的错误。我已经修正了我的答案:)构建队列..@epascarello最小代码?@mouadenaciri:第一次迭代计划在0秒后调用函数,第二次迭代计划在1秒后调用函数,第三次迭代计划在2秒后调用函数,等等。第一次超时为0,下一次为1xdelay,下一个比摆弄好多了。reduce
:D有时我忘了是哪一年了。。。