function p(flag){ return new Promise((resolve , reject)=>{ if(flag){ resolve('ok'); }else{ reject('no'); } }); } function a(){ alert('a'); } function b(){ alert('b'); } p(true).then((msg)=>{ alert(msg); },(err)=>{ alert(err); }).then(a).then(b)
var p = new Promise((resolve, reject) => { console.log('创建Promise 实例'); $.getScript('https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/js/lib/jquery-1.10.2_d88366fd.js').done(function(){ alert(1); resolve('resolve 被执行'); }).fail(function(){ reject('reject 被执行'); }); }) var p1 = new Promise((resolve, reject)=>{ $.getScript('https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/js/min_super_af0391fe.js').done(function(){ resolve('aaaa'); }).fail(function(e){ reject(e) }) }); Promise.all([p,p1]).then(function(msg){ console.log(msg); //["resolve 被执行", "aaaa"] })
var p = new Promise(function(resolve){ setTimeout(()=>{ console.log(1) resolve('aaaaaaa'); }, 3000); }); var p1 = new Promise((resolve)=>{ setTimeout(()=>{ console.log(2) resolve('bbbbb'); }, 1000); }); Promise.all([p,p1]).then((msg)=>{ console.log(msg) }); //2 //1 //["aaaaaaa", "bbbbb"]
function timeout (ms) { return new Promise((resolve, reject) => { setTimeout(resolve, ms, 'done'); }) } timeout(2000).then((value) => { console.log(value); })
const promise = new Promise((resolve, reject)=>{ console.log('Promise'); resolve(111); }) promise.then((value)=> { console.log('resolve', value) }) console.log('Hi')
function loadImageAsync (url) { return new Promise((resolve, reject) => { const img = new Image(); img.onload = () => { resolve(img); } img.onerror = () => { reject(new Error('Could not load image at ' + url)) } img.src = url; }) } loadImageAsync('http://img.ivsky.com/img/fbizhi/co/201709/01/tanghongde_liange-004.jpg').then((img) => { console.log(img) })
function getJSON (url) { return new Promise((resolve, reject)=> { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler () { if (this.readyState !== 4) { return; } if (this.status == 200) { resolve(this.response); } else { reject(new Error(this.statusText)) } } }) } getJSON('./js/test.json').then((res) => { console.log(res) }, (err) =>{ console.error('出错咯', err) })
const p1 = new Promise((resolve, reject) => { setTimeout(()=> { console.log('p1') reject(new Error('reject')) }, 3000) }) const p2 = new Promise((resolve, reject) => { setTimeout(() =>{ console.log('p2') resolve(p1) }, 1000); }) p2.then((result) => { console.log(result) }).catch(error => console.log(error))
new Promise((resolve, reject) => { resolve(2) console.log(1); }).then((value)=>{ console.log(value) })