Promise简析
生成实例:
const promise = new Promise((resolve,reject)=>{
//成功时执行,走then
resolve()
//失败时执行,走catch
reject()
})
promise实例.then(成功的函数,失败的函数(可选))
//摘自阮一峰-ES6
let promise = new Promise(function(resolve, reject) {
console.log('Promise');
resolve();
});
promise.then(function() {
console.log('resolved.');
});
console.log('Hi!');
// Promise
// Hi!
// resolved
所以一般写成函数接收的形式:异步加载图片:参考: 阮一峰-Promise
function loadImageAsync(url) {
return new Promise(function(resolve, reject) {
const image = new Image();
image.onload = function() {
resolve(image);
};
image.onerror = function() {
reject(new Error('Could not load image at ' + url));
};
image.src = url;
});
}