首页 > 解决方案 > 睡眠功能没有按预期工作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);

};

`

标签: javascriptnode.jspromise

解决方案


使用for循环而不是.map()循环遍历数组。

for (const [index, id] of data.Item.json.entries()) {
  setTimeout(() => activityService.streamActivity(id), (5 + index) * 6000);
}


推荐阅读