promise对象用于延迟计算和异步计算:一个promise对象代表着一个还未完成,但预期将来完成的操作
打印结果如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> console.time("Promise"); //resolve执行成功后调用 //reject执行失败时调用 new Promise(function(resolve, reject) { setTimeout(function() { resolve("定时器"); }, 1000 * 2); }).then(function(result) { console.log(result); console.timeEnd("Promise"); }); </script> </body> </html>
必须要加返回值
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> </body> <script> console.time('Promise'); //resolve 执行成功后调用 //reject 执行失败时调用 new Promise(function(resolve,reject){ setTimeout(function(){ resolve("定时器执行完毕"); },1000*2); }).then(function(result){ console.log("第一个 then 有异步"); //对数据做处理 return new Promise(function(resolve, reject){ setTimeout(function(){ resolve({ "data" : result }); },1000 * 2); }); }).then(function(data){ //接收完整的数据 console.log(data); console.timeEnd('Promise'); }); </script> </html>