我已经尝试过阅读指南和教程来异步/等待,但我似乎无法在任何地方找到这个.
这是有问题的代码:
var func1 = new Promise((resolve, reject) => {
console.log("Func1");
setTimeout(() => {
resolve(10);
}, 100);
});
var func2 = new Promise((resolve, reject) => {
console.log("Func2");
setTimeout(() => {
resolve(20);
}, 5000);
})
let run = async() => {
let var1 = await func1;
let var2 = await func2;
console.log(var1);
console.log(var2);
}
run();Run Code Online (Sandbox Code Playgroud)
我们看到"Func1"和"Func2"立即打印,一个接一个.5秒后,在func2中指定超时,我们打印"10"和"20".到现在为止还挺好.
但是,如果我将最后一段代码更改为:
let run = async() => {
let var1 = await func1;
console.log(var1);
let var2 = await func2;
console.log(var2);
}
Run Code Online (Sandbox Code Playgroud)
然后我看到"Func1"立即打印,但"Func2"也是如此,即使console.log(var1)它在它之前.100ms后"10",然后5秒后"20".
来自MDN:
await表达式导致异步函数执行暂停,直到Promise被完成或拒绝,并在执行后继续执行async函数. …
Create-react-app 附带一个 registerServiceWorker.js 文件,其中包含注册服务工作者的代码。我只是有点困惑它是如何工作的。有问题的代码是:
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is …Run Code Online (Sandbox Code Playgroud)