异步编程的一种解决方案
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
Math.random() * 100 > 60 ? resolve('ok') : reject('no')
})
})
promise.then(val => {
console.log(val);
}, reason => {
console.log(reason);
})
var promise = new Promise(function(resolve, reject){
setTimeout(function(){
Math.random() * 100 > 60 ? resolve('ok') : reject('no')
})
})
promise.then(val => {
console.log(val);
return 1
}, reason => {
console.log(reason);
return 2
}).then(val => {
console.log('then2-', val);
}, reason => {
console.log('then2-', reason);
})
var promise = new Promise(function(resolve, reject) {
setInterval(function() {
Math.random() * 100 > 60 ? resolve('ok') : reject('no')
})
})
promise.then(val => {
console.log(val);
return new Promise((resolve, reject) => {
resolve('new promise')
})
}, reason => {
console.log(reason);
return 2
}).then(val => {
console.log('then2-', val);
}, reason => {
console.log('then2-', reason);
})
var promise = new Promise((resolve, reject) => {
resolve(a);
})
promise.then((val) => {
console.log('resolve', val);
}, (reason) => {
console.log('reject', reason);
})
var promise = new Promise((resolve, reject) => {
resolve(a);
})
promise.then(null, (reason) => {
console.log('reject', reason);
})
promise.catch((reason) => {
console.log('reject', reason);
})
var promise = new Promise((resolve, reject) => {
resolve('ok');
console.log(a); // 这个报错因为状态固化,无法被捕获
})
promise.then((val) => {
console.log('res', val);
}).catch((reason) => {
console.log('reject', reason);
})