如何使用 async 或 promise 添加带有 setTimeout 的随机延迟

Abh*_*yar 1 javascript asynchronous settimeout es6-promise

如果我想使用 setTimeout 和delay = Math.random() * 1000. 由于异步编程和事件循环,答案将是从 1 到 10 以随机顺序排列的数字。

我想要的是以上述相同的延迟按递增顺序打印数字。这可以通过 Promises 或 Async 模块来完成。我的意思是说它应该只打印一次,然后打印 2,依此类推。

任何帮助,将不胜感激。

注意:请不要给出诸如为变量添加时间并将该变量用作延迟之类的答案。

Aro*_*ron 5

You could do this like this, using Promises and async/await

// returns a promise that resolves after the specified number of ms
function delay(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}

// function that will print the numbers in correct order, with delays
async function print(num) {
    for (let i = 1; i <= num; i++) {

        await delay(Math.random() * 1000); // wait 

        console.log(i); // print number
    }
}

print(10); // actually execute function
Run Code Online (Sandbox Code Playgroud)

The function that actually prints the numbers is an async function, using a delay based on a promise that resolves after the specified number of milliseconds.