Promise:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> //生成一个0-2之间的随机数,如果小于1,则等待一段时间后返回成功,否则返回失败 function test(resolve, reject) { var timeOut = Math.random() * 2; console.log('set timeout to: ' + timeOut + ' seconds.'); setTimeout(function () { if (timeOut < 1) { console.log('call resolve()...'); resolve('200 OK');//成功的时候调用 } else { console.log('call reject()...'); reject('timeout in ' + timeOut + ' seconds.'); //失败的时候调用 } }, timeOut * 1000); } // var promise = new Promise(test); // promise.then(function(result){ // console.log('成功:', result);//200 OK // }) // promise.catch(function(result){ // console.log("失败",result) // }) var promise = new Promise(test).then(function(res){ console.log('成功:', res);//200 OK }).catch(function(res){ console.log("失败",res) }) </script> </body> </html>