JavaScript promise resolving with setTimeout

余生长醉 提交于 2019-12-08 11:45:58

问题


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.

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 )
  );

回答1:


/* 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 );

here you actually resolve the promise (you execute the result function) and pass the result to the setTimeout function.

Writing

() => resolve( 'Job\'s done!!!' )

is the same as

function() {
    resolve( 'Job\'s done!!!' );
}


来源:https://stackoverflow.com/questions/46551778/javascript-promise-resolving-with-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!