const foo = () => {
console.log('ok')
return Promise.resolve(1);
}
let bar = foo(); // line 1
bar.then(() => { // line 2
bar = foo(); // line 3
})
想知道为什么第 3 行不刷新第 2 行
导致无限
1. promise 解决
2. 重新实例化 bar
回到 1.
如果您真的希望它如上所述无限循环,您将如何在不编写回调 hell 的情况下更改此代码?
最佳答案
这是无限循环的方法。为了不完全阻塞浏览器,我添加了一个 setTimeout
,这样 promise 只会在大约半秒后解析:
const foo = () => {
console.log('ok');
// Lets give the browser some air to breathe...
return new Promise(resolve =>
setTimeout(() => resolve(1), 500)
);
}
const loop = async () => {
while (true) await foo();
};
loop();
没有 async
await
语法:
const foo = () => {
console.log('ok');
// Lets give the browser some air to breathe...
return new Promise(resolve =>
setTimeout(() => resolve(1), 500)
);
}
const loop = () => {
foo().then(loop);
};
loop();
关于javascript - promise 无限回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56875847/