您的位置:首页 > 其它

es6 Promise 的应用

2018-01-28 18:00 120 查看


Promise 的应用


加载图片

我们可以将图片的加载写成一个
Promise
,一旦加载完成,
Promise
的状态就发生变化。
const preloadImage = function (path) {

return new Promise(function (resolve, reject) {

const image = new Image();

image.onload  = resolve;

image.onerror = reject;

image.src = path;

});

};



Generator 函数与 Promise 的结合

使用 Generator 函数管理流程,遇到异步操作的时候,通常返回一个
Promise
对象。
function getFoo () {

return new Promise(function (resolve, reject){

resolve('foo');

});

}


const g = function* () {

try {

const foo = yield getFoo();

console.log(foo);

} catch (e) {

console.log(e);

}

};


function run (generator) {

const it = generator();


function go(result) {

if (result.done) return result.value;


return result.value.then(function (value) {

return go(it.next(value));

}, function (error) {

return go(it.throw(error));

});

}


go(it.next());

}


run(g);


上面代码的 Generator 函数
g
之中,有一个异步操作
getFoo
,它返回的就是一个
Promise
对象。函数
run
用来处理这个
Promise
对象,并调用下一个
next
方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: