先看下面一个例子:
const delay = () => {
setTimeout(() => {
console.log('hello');
}, 100);
};
const atOnce = () => {
console.log('world');
};
const test = () => {
delay();
atOnce();
};
test();
// 输出结果
// world
// hello
delay
函数设定 100 毫秒后输出字符串 hello
。在 test
函数中 delay()
在 atOnce
上方。
但 Javascript 执行时代码并非线性地运行,并不会等待 delay()
执行完毕再去执行 atOnce
。所以我们看到先输出 world
再输出 hello
。
如果需要等待 delay
函数执行完毕后再执行 atOnce
函数,下面演示几种方法。
使用 Promise 和 then
const delay = () => {
let promise = new Promise((resolve, reject) => {
setTimeout(resolve('hello'), 100);
});
return promise;
};
const atOnce = () => {
console.log('world');
};
delay()
.then((value) => {
console.log(value)
})
.then(atOnce)
// 输出
// hello
// world
使用 Generator
const delay = () => {
let promise = new Promise((resolve, reject) => {
setTimeout(resolve('hello'), 100);
});
return promise;
};
const atOnce = () => {
console.log('world');
};
function* gen(){
yield delay();
atOnce();
};
var g = gen();
var result = g.next();
result.value
.then((data) => {
console.log(data)
})
.then(() => {g.next()});
// 输出
// hello
// world
使用 async 和 await
const delay = async () => {
let promise = new Promise((resolve, reject) => {
setTimeout(resolve('hello'), 100);
});
return promise;
};
const atOnce = () => {
console.log('world');
};
const test = async () => {
const v = await delay();
console.log(v);
atOnce();
}
test()
// 输出
// hello
// world
网友评论