<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id="button">按钮一下</button> <script> function rand(m, n) { return Math.ceil(Math.random() * (n - m + 1)) + m - 1; } const btn = document.querySelector("#button") btn.addEventListener('click', function () { const p = new Promise((resolve, reject) => { setTimeout(() => { let n = rand(1, 100) if (n < 30) { resolve(n) //将promise对象的状态设置为成功 } else { reject(n) //将promise对象的状态设置为失败 } }, 1000) }) p.then((value) => { alert("成功了"); }, (reason) => { alert("失败了"); }) }) //resolve表示 </script> </body> </html>
在这里的resolve(n)表示将正确的原因传给resolve,函数获得回调值n。同时将错误的原因传给reject(),函数获得回调值n,并且使用回调,将值传给p.then()的成功的,将错误的值传给p.then()的错误的