JavaScript承诺使用setTimeout解决 [英] JavaScript promise resolving with setTimeout

查看:75
本文介绍了JavaScript承诺使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆