[英]sleep function not working as expected nodejs
你好,我正在編寫一個 nodejs 函數,它使用 array.map 發送請求,但我想讓函數在 4 分鍾內等待或休眠,然后在發送下一個請求之前出現錯誤,我嘗試使用 sleep 但map 函數不等待發送下一個請求前 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); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.