Javascript 如何使用setTimeout和promises使此JS代码更具功能?
我正在尝试学习如何使用更多的函数和更少的循环,以更实用的方式编写代码。我想在调用connectBing之间实现一个超时。我想知道是否可以不使用I变量,在迭代之间仍然有1秒的超时。我的代码目前可以工作,但我正在寻找其他方法来编写它而不使用I 这是我的代码:Javascript 如何使用setTimeout和promises使此JS代码更具功能?,javascript,node.js,asynchronous,functional-programming,Javascript,Node.js,Asynchronous,Functional Programming,我正在尝试学习如何使用更多的函数和更少的循环,以更实用的方式编写代码。我想在调用connectBing之间实现一个超时。我想知道是否可以不使用I变量,在迭代之间仍然有1秒的超时。我的代码目前可以工作,但我正在寻找其他方法来编写它而不使用I 这是我的代码: // MAIN getAllPosts().then((posts) => { posts .forEach( (post, i) => { setTimeout(() => {
// MAIN
getAllPosts().then((posts) => {
posts
.forEach( (post, i) => {
setTimeout(() => {
connectBing(anchorText,console.log).then()
} ,i * 1000)
})
// CONNECT TO BING WITH KW AND DO SOMETHING
function connectBing(anchorText,doSomethingWithBing) {
var deferred = q.defer();
request('https://www.cnn.com/search?q=' + anchorText, function (error, response, body) {
error ? console.log('error:', error) :
console.log('statusCode:', response && response.statusCode);
(doSomethingWithBing) ? doSomethingWithBing(body) : "You didn't give connectBing anything to do!"
})
return deferred.promise
}
您可以获取一个异步函数数组,并将每个异步函数链接起来,以便在另一个异步函数之后运行。我将使用本机承诺进行演示,您可以将其映射到您正在使用的库 首先创建一个接受异步函数数组的函数。它将一个接一个地链接,返回最后一个:
function chainAsyncFns(fns) {
// Ensure we have at least one promise to return
let promise = Promise.resolve();
fns.forEach(fn => promise = promise.then(fn));
return promise;
}
然后,为每个post创建一个异步函数,该函数将调用connectBing
,然后等待超时:
function connectBing() {
// Pretend we are connecting to a data source
return Promise.resolve();
}
function delay(ms) {
// Return a promise that resolves when the timeout is up
return new Promise(resolve => setTimeout(resolve, ms));
}
let fns = posts.map(post => () => {
return connectBing()
.then(() => delay(1000))
.catch(() => console.log('error'));
});
将功能链接到一个接一个地运行:
chainAsyncFns(fns).then(() => console.log('done'));
按照您当前编写的方式,迭代之间不会有1秒的超时,而是有1秒的超时。。。。不知道你要什么…你想做什么?在这里,如果你有1k个查询,它会在1k秒内产生1k个查询。在我的理解中,你正在寻找一个并发的模型,不要对服务器进行垃圾邮件,并以更高的速率保持事物的处理。如果在处理的中间出现错误SWPAN会发生什么?@ MH CBON好问题,我不确定这个例子有多远。我更新了示例以捕获创建异步函数时的错误。