gpt4 book ai didi

javascript - 添加计时器到 Promise.all、map

转载 作者:行者123 更新时间:2023-12-01 02:33:58 25 4
gpt4 key购买 nike

我想在下面的获取请求之间添加一些超时。我的意思是,流程应该如下所示: timeout, https://example.com/example1, timeout, https://example.com/example2, timeout, https://example.com/example3, timeout 等(或者没有第一次超时,无论如何)。

以下功能正常工作:

function promiseGetInformationFromMultipleUrls(parts) {
return Promise.all(parts.map(part => {
return request({
'url': `https://example.com/${part}`,
'json': true
}).then(partData => {console.log("Part data was fetched: " + part); return partData.result;})
.catch(err => {console.error("Error during fetching data from part: " + part + ", error code: " + err.statusCode);});
}));
}

其中部分是 -> example1、example2、example3...

我正在尝试通过添加计时器来做到这一点:

const timer = ms => new Promise( res => setTimeout(res, ms));

并使用它:

function promiseGetInformationFromMultipleUrls(parts) {
return Promise.all(parts.map(part => {
console.log("wait 1 seconds");
timer(1000).then(_=>console.log("done"));
return request({
'url': `https://example.com/${part}`,
'json': true
}).then(partData => {console.log("Part data was fetched: " + part); return partData.result;})
.catch(err => {console.error("Error during fetching data from part: " + part + ", error code: " + err.statusCode);});
}));
}

但这是错误的流程 -> 超时,超时,超时,...,获取请求1,获取请求2,获取请求3

最佳答案

您可以将其简化为 Promise 链:

function promiseGetInformationFromMultipleUrls(parts) {
return parts.reduce((chain, part) =>
chain.then((result) =>
timer(1000).then(() =>
request(/*...*/).then(res =>
result.concat(res)
)
)
),
Promise.resolve([])
);
}

但是这很丑陋,所以你可以使用 async/wait 来代替:

 async function promiseGetInformationFromMultipleUrls(parts){
const result = [];
for(const part of parts){
await timer(1000);
result.push(await request(/*...*/));
}
return result;
}

关于javascript - 添加计时器到 Promise.all、map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48093956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com