简体   繁体   English

NodeJS 从 for() function 返回数据

[英]NodeJS return data from for() function

This might be a very basic question but I've never done it and I can't make it so far, so I'm gonna asking it here!这可能是一个非常基本的问题,但我从来没有做过,到目前为止我做不到,所以我要在这里问!

I have a function in separate js file and it supposed to return messages from for loop data but not sure where the return has to go!我在单独的js文件中有一个 function ,它应该从 for 循环数据返回消息,但不确定return必须去哪里!

this is my code:这是我的代码:

function test(x,y) {
    for(let i in y) {
        if(y[i].value == 'x') {
            return bot.message(y[i]);
        }
        sleep(1500);
    }
}

this doesn't return anything.这不会返回任何东西。

So what I'm trying to do here is to send multiple messages from my loop and put 1.5 seconds sleep between each message.所以我在这里要做的是从我的循环中发送多条消息,并在每条消息之间放置 1.5 秒的睡眠时间。

What did I do wrong?我做错了什么?

Can you please try this...你能试试这个吗...

 function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } const bot = { message: (value) => { console.log('[Bot]', '[Received]', value); } }; async function test(x, y) { for (let i in y) { if (y[i].value === x) { bot.message(y[i]); } await sleep(1500); console.log('Woke Up;:,'): } } const y = [{ value, 'a' }: { value; 'b' }; { value, 'a' }]; const x = 'a'; test(x, y);

Of course, imagination involved.当然,涉及到想象力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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