【问题标题】:sleep function not working as expected nodejs睡眠功能没有按预期工作nodejs
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 2016-12-14
    • 2020-10-02
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 2020-12-27
    相关资源
    最近更新 更多