简体   繁体   中英

sleep function not working as expected nodejs

hello i am writing a nodejs function that send requests in using array.map but i want to make the function wait or sleep during 4min when there is an error before sending the next request ,i have tried to use sleep but the map function doesnt wait 4 min before sending the next request:

here is the map function : data.Item.json.map(( id, index ) => setTimeout(()=> activityService.streamActivity(id),(5+index) * 6000))

and there is the called function inside the map :`

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);

};

`

Use a for loop instead of .map() to loop through the array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM