[英]Why can I not call resolve() for Promises in SetTimeout Function directly
I have two versions of a sleep function, one is waiting for the resolve the other isn't:我有两个版本的睡眠功能,一个正在等待解决,另一个不是:
function sleephelper1(ms) {
return new Promise(function(resolve) {
setTimeout(() => resolve('done'), ms);
})
}
function sleephelper2(ms) {
return new Promise(function(resolve) {
setTimeout(resolve('done'), ms);
})
}
Then I call either sleephelper1 or sleephelper2:然后我调用 sleephelper1 或 sleephelper2:
async function test(){
var test = await sleephelper1(3000);
console.log(test)
console.log("exit test function")
}
test()
The first one is waiting 3 seconds before in resolves.第一个在解析前等待 3 秒。 But sleephelper2 ist not working properly.
但是 sleephelper2 无法正常工作。 The code gets executed immediatly.
代码立即执行。 I thought that SetTimeout can delay the call of a function by a given amount of time.
我认为 SetTimeout 可以将函数的调用延迟给定的时间。 Is resolve() not a function ?
resolve() 不是函数吗? I have found this post JavaScript promise resolving with setTimeout which is quite what I am asking here, exept that I am using async await.
我发现这篇文章使用 setTimeout 解决 JavaScript 承诺,这正是我在这里问的问题,除了我使用的是异步等待。 Also I did not get the explanation.
我也没有得到解释。 Could somebody explain to me why this behaves the way it does ?
有人可以向我解释为什么会这样吗?
setTimeout(() => resolve('done'), ms);
This means "create a function with the text () => resolve('done')
and pass it into setTimeout".这意味着“使用文本
() => resolve('done')
创建一个函数并将其传递给 setTimeout”。 setTimeout will wait the specified amount of time, and then call that function. setTimeout 将等待指定的时间量,然后调用该函数。
setTimeout(resolve('done'), ms);
This means "immediately call resolve('done')
and pass its result into settimeout".这意味着“立即调用
resolve('done')
并将其结果传递给 settimeout”。 the return value from resolve is undefined
, so undefined is passed into setTimeout. resolve 的返回值是
undefined
,所以 undefined 被传递到 setTimeout 中。 There is thus no function for setTimeout to run 3 seconds later.因此, setTimeout 没有功能可以在 3 秒后运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.