1、模拟抽奖
<body> <div class="container"> <h2 class="page-header">promise初体验</h2> <button class="btn btn-primary" id="btn">点击抽奖</button> </div> <script> function rand(m, n) { return Math.ceil(Math.random() * (n - m + 1) + m - 1) } const btn = document.querySelector('#btn') btn.addEventListener('click', function () { // 使用promise const p = new Promise((resolve, reject) => { setTimeout(() => { let n = rand(1, 100) if (n <= 30) { resolve() } else { reject() } }, 1000); }) p.then(() => { alert('恭喜') }, () => { alert('再接再厉') }) }) </script> </body>
2、promise实践练习-fs模块
const fs = require('fs') const p = new Promise((resolve,reject)=>{ fs.readFile('./ziyuan/wenju.txt',(err,data)=>{ if(err) reject(err) resolve(data) }) }) p.then(value=>{ console.log(value.toString()); },reason=>{ console.log(reason); )}