javascript - 睡眠功能没有按预期工作nodejs
问题描述
您好,我正在编写一个使用 array.map 发送请求的 nodejs 函数,但我想让函数在 4 分钟内等待或休眠,当发送下一个请求之前出现错误时,我尝试使用休眠,但映射函数不等待发送下一个请求前 4 分钟:
这是地图功能:
data.Item.json.map(( id, index ) => setTimeout(()=> activityService.streamActivity(id),(5+index) * 6000))
并且地图中有被调用的函数:`
const streamActivity = (client) => (activityId) => {
return new Promise((resolve, reject) => {
client.streams.activity(
{
id: activityId,
types:
"time,heartrate,velocity_smooth,altitude,distance,latlng,cadence,watts,temp,moving,grade_smooth,average_speed",
resolution: "high",
},
async function (err, payload,next) {
if (!err ) {
//save to dynamodb
var params = {
TableName: "streams",
Item: {
"id":activityId,
"json": payload,
}
};
docClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add movie", ". Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("PutItem succeeded:" +activityId);
}
});
} else {
await sleep(60000)
}
}
);
});
// setInterval(streamActivity,5000);
};
`
解决方案
使用for
循环而不是.map()
循环遍历数组。
for (const [index, id] of data.Item.json.entries()) {
setTimeout(() => activityService.streamActivity(id), (5 + index) * 6000);
}
推荐阅读
- r - 带有 tsmp R 包的自定义注释向量
- java - 通过服务器处理数据包导致 CPU 大幅增加
- macos - AnzoGraph docker 支持 Mac m1
- blazor - 如何通过单击 blazor 中的按钮将数据从 foreach 循环传递到另一个页面
- r - 替换字符串中的重复字符
- database - 如果我不在 Laravel Eloquent 的刀片视图中呈现 db 列值,用户能否看到它们?
- javascript - React 不适用于 js Set:s(数据类型)吗?
- python - For 循环没有正确地将信息附加到二维数组中
- javascript - SwiperJS - 在同一页面上运行 2 张不同的幻灯片。幻灯片 2 导致溢出和间距问题
- r - R 分组频率表