Javascript 如果使用wait,同步使用setTimeout会停止代码吗?
下面的代码只提供了 “超时前”和“内” 但不是“超时后”。 为什么会这样Javascript 如果使用wait,同步使用setTimeout会停止代码吗?,javascript,promise,async-await,settimeout,Javascript,Promise,Async Await,Settimeout,下面的代码只提供了 “超时前”和“内” 但不是“超时后”。 为什么会这样 async function asy() { console.log('before timeout'); await awa(); console.log('after timeout'); } async function awa() { return new Promise(resolve => {setTimeout(function(){console.log('within');
async function asy() {
console.log('before timeout');
await awa();
console.log('after timeout');
}
async function awa() {
return new Promise(resolve => {setTimeout(function(){console.log('within');}, 600);
}
asy();
因为你从来没有解决过承诺,所以它永远悬着
return new Promise(resolve => {setTimeout(function(){console.log('within');}, 600);
^^^^^^^
NEVER USED
您还没有解决返回后的承诺,因此输出
async function asy() {
console.log('before timeout');
await awa();
console.log('after timeout');
}
async function awa() {
return new Promise(resolve => {
setTimeout(function(){
console.log('within');
resolve();
}, 600);
}
asy();
wait
在执行以下表达式之前,等待承诺得到解决
或被拒绝
,在函数awa()之前不需要异步:
兑现诺言
this.driverWait = async function (explicitWaitMS) {
// create a new promise inside of the async function
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(true), explicitWaitMS) // resolve
});
// wait for the promise to resolve
await promise;
}
语言是什么async/await
最早由C#引入。这不是C#很确定这是JavaScript@PanagiotisKanavos@Liam或者Typescript,这就是为什么我问它为什么不是editingTypescript是Javascript的超集,它将在两者中运行,但最终它是Javascript。可能正在节点上运行,但OP需要对此进行确认回调需要调用resolve()?
this.driverWait = async function (explicitWaitMS) {
// create a new promise inside of the async function
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(true), explicitWaitMS) // resolve
});
// wait for the promise to resolve
await promise;
}