如何用 promises 控制 setTimeout
How to control setTimeout with promises
var functionsArray = [
function() {
setTimeout(function() {
console.log(1);
}, 100);
},
function() {
setTimeout(function() {
console.log(2);
}, 200);
},
function() {
setTimeout(function() {
console.log(3);
}, 10);
}
],
假设我有一个像上面这样的函数数组(其中的函数数量未知)。我想写一个函数,它将这个数组作为参数并按顺序执行它们。在上面的示例中,我希望它按顺序记录 1、2、3。由于Promise.all不保证执行顺序,是否可以在没有回调地狱的情况下实现?
您无法从仅调用 setTimeout
的函数中获得承诺 - 它需要一些帮助,例如:
function after(n, f) {
return () => new Promise(resolve => {
setTimeout(() => {
resolve(f());
}, n);
});
}
使用情况:
var functionsArray = [
after(100, () => console.log(1)),
after(200, () => console.log(2)),
after( 10, () => console.log(3)),
];
使用该数组,您可以依次 await
每个函数:
for (let f of functionsArray) {
await f();
}
您可以编写一个简单的 setTimeout Promise 函数:
function timeoutPromise(time = 0){
return new Promise(resolve => setTimeout(resolve, time)
}
await timeoutPromise(10);
console.log('waited 10 sec')
timeoutPromise(20).then(() => console.log('waited 20 sec')
//make a new array as you like
Promise.all([
timeoutPromise(100).then(() => console.log(1)),
timeoutPromise(200).then(() => console.log(2)),
timeoutPromise(300).then(() => console.log(3))
])
var functionsArray = [
function() {
setTimeout(function() {
console.log(1);
}, 100);
},
function() {
setTimeout(function() {
console.log(2);
}, 200);
},
function() {
setTimeout(function() {
console.log(3);
}, 10);
}
],
假设我有一个像上面这样的函数数组(其中的函数数量未知)。我想写一个函数,它将这个数组作为参数并按顺序执行它们。在上面的示例中,我希望它按顺序记录 1、2、3。由于Promise.all不保证执行顺序,是否可以在没有回调地狱的情况下实现?
您无法从仅调用 setTimeout
的函数中获得承诺 - 它需要一些帮助,例如:
function after(n, f) {
return () => new Promise(resolve => {
setTimeout(() => {
resolve(f());
}, n);
});
}
使用情况:
var functionsArray = [
after(100, () => console.log(1)),
after(200, () => console.log(2)),
after( 10, () => console.log(3)),
];
使用该数组,您可以依次 await
每个函数:
for (let f of functionsArray) {
await f();
}
您可以编写一个简单的 setTimeout Promise 函数:
function timeoutPromise(time = 0){
return new Promise(resolve => setTimeout(resolve, time)
}
await timeoutPromise(10);
console.log('waited 10 sec')
timeoutPromise(20).then(() => console.log('waited 20 sec')
//make a new array as you like
Promise.all([
timeoutPromise(100).then(() => console.log(1)),
timeoutPromise(200).then(() => console.log(2)),
timeoutPromise(300).then(() => console.log(3))
])