简体   繁体   English

打印连续数字,不能修改功能

[英]Printing consecutive numbers, can't modify function

I've been in some technical interviews, this one got me frustrated as I can't modify the existent function and need to print 5 consecutive numbers (Number: 1, Number: 2, Number: 3....) plus the Promise我参加过一些技术面试,这让我很沮丧,因为我无法修改现有的功能,需要打印 5 个连续的数字(数字:1,数字:2,数字:3....)加上 Promise

console.log('Logging Num 1');
const printNumber = (number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`Number: ${number}`);
      resolve();
    }, Math.floor(Math.random() * 10));
  });
};

printNumber(1);
printNumber(2);

This was the hint, I remembered this one for looping through elements这是提示,我记得这是循环元素的提示

for(let i = 1; i <= 5; i+= 1) 

But how can I add this in the code without modifying the function?但是如何在不修改函数的情况下将其添加到代码中呢? Yes I got nervous and confused.是的,我感到紧张和困惑。

You should be able to do this你应该能够做到这一点

const syncLog = async (x) => {
    for(let i = 0; i < x; i++){
        await printNumber(i)
    }
}

syncLog(5)

>> Number: 0
>> Number: 1
>> Number: 2
>> Number: 3
>> Number: 4

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

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