JavaScript承诺使用setTimeout解决 [英] JavaScript promise resolving with setTimeout
问题描述
我不明白为什么第一个setTimeout函数起作用,而第二个函数不起作用。当我运行第二个setTimeout时,第一个被注释掉。
I don't understand why the first setTimeout function works but the second one doesn't. The first one is commented out when I run the second setTimeout. But instead of resolving after 3 seconds it resolves immediately.
我对整个承诺事物是陌生的,而我正在研究的教程使用setTimeout a的promise
I'm new to the whole 'promise' thing and the tutorial I'm working through uses promises with setTimeout a lot.
let promise = new Promise( ( resolve, reject ) => {
/* why does setTimeout work with this one... */
setTimeout( () => resolve( 'Job\'s done!!!' ), 3000 );
/* but not with this one */
setTimeout( resolve('done'), 3000 );
} );
promise.then(
result => alert( result )
);
推荐答案
/* why does setTimeout work with this one... */
setTimeout( () => resolve( 'Job\'s done!!!' ), 3000 );
发生超时时,您调用函数()=> ...
直到执行完成为止
when the timeout occur you call a function () => ...
wich when executed till resolve the promise
/* but not with this one */
setTimeout( resolve('done'), 3000 );
在这里,您实际解决了promise(执行result函数)并将结果传递给setTimeout函数
here you actually resolve the promise (you execute the result function) and pass the result to the setTimeout function.
写作
() => resolve( 'Job\'s done!!!' )
与
is the same as
function() {
resolve( 'Job\'s done!!!' );
}
这篇关于JavaScript承诺使用setTimeout解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!