【发布时间】:2021-07-06 11:25:09
【问题描述】:
你好,我正在编写一个 nodejs 函数,它使用 array.map 发送请求,但我想让函数在 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);
};
`
【问题讨论】:
-
在
.map()内部?您不能在地图内等待。如果要在其中等待,则必须使用for循环 -
正如所写,
streamActivity()是一个返回函数的函数(所谓的工厂),但它不是这样调用的。
标签: javascript node.js promise