const promise = new Promise(function (resolve, reject) {
reject(new Error('promise rejected'))
})
promise.then(function (value) {
console.log('resolved', value)
}, function (error) {
console.log('rejected', error)
})
console.log('end')
function ajax(url){
return new Promise((resolve,reject)=>{
const xhr = new XMLHttpRequest();
xhr.open('get',url);
xhr.onload = function (){
if (this.status === 200) {
resolve(this.response);
}else{
reject(new Error(this.statusText));
}
}
})
}
ajax('/api/foo.json').then(function (res) {
console.log(res)
}, function (error) {
console.log(error)
})
ajax('/api/urls.json').then(function (urls) {
ajax(urls.users).then(function (users) {
ajax(urls.users).then(function (users) {
ajax(urls.users).then(function (users) {
ajax(urls.users).then(function (users) {
})
})
})
})
})
function ajax (url) {
return new Promise(function (resolve, reject) {
resolve({ok:'ok'});
})
}
ajax()
.then(function (value) {
console.log('promise',value)
return ajax()
})
.then(function (value) {
console.log('promise',value)
return 'val';
})
.then(function (value) {
console.log('val',value)
return null
})
.then(function (value) {
console.log('null:',value)
return undefined;
})
.then(function (value) {
console.log('undefined:',value);
})
.then(function (value) {
console.log('无return:',value);
})
function ajax (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'json'
xhr.onload = function () {
if (this.status === 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
xhr.send()
})
}
ajax('/api/users11.json')
.then(function onFulfilled (value) {
console.log('onFulfilled', value)
}, function onRejected (error) {
console.log('onRejected', error)
})
ajax('/api/users11.json')
.then(function onFulfilled (value) {
console.log('onFulfilled', value)
})
.catch(function onRejected (error) {
console.log('onRejected', error)
})
ajax('/api/users11.json')
.then(function onFulfilled (value) {
console.log('onFulfilled', value)
})
.then(undefined, function onRejected (error) {
console.log('onRejected', error)
})
ajax('/api/users.json')
.then(function onFulfilled (value) {
console.log('onFulfilled', value)
return ajax('/error-url')
}, function onRejected (error) {
console.log('onRejected', error)
})
ajax('/api/users.json')
.then(function onFulfilled (value) {
console.log('onFulfilled', value)
return ajax('/error-url')
})
.catch(function onRejected (error) {
console.log('onRejected', error)
})
window.addEventListener('unhandledrejection', event => {
const { reason, promise } = event
console.log(reason, promise)
event.preventDefault()
}, false)
process.on('unhandledRejection', (reason, promise) => {
console.log(reason, promise)
})