【Using promises】
过去,异步方法这样写:
function successCallback(result) { console.log("It succeeded with " + result); } function failureCallback(error) { console.log("It failed with " + error); } doSomething(successCallback, failureCallback);
使用promise后,异步方法这样写:
let promise = doSomething();
promise.then(successCallback, failureCallback);
promise模式有以下几个好处:
1、回调方法永远在下一帧后才会调用。即使当前帧已完成。
2、可以通过串连.then,设置多个回调。
promise模式可以用于解决死亡金字塔问题:
doSomething(function(result) { doSomethingElse(result, function(newResult) { doThirdThing(newResult, function(finalResult) { console.log('Got the final result: ' + finalResult); }, failureCallback); }, failureCallback); }, failureCallback);
doSomething().then(function(result) { return doSomethingElse(result); }) .then(function(newResult) { return doThirdThing(newResult); }) .then(function(finalResult) { console.log('Got the final result: ' + finalResult); }) .catch(failureCallback);
catch(failureCallback)
是 then(null, failureCallback) 的简单写法
使用new Promise((resolve, reject)=>{})创建 Promise。Basically, the promise constructor takes an executor function that lets us resolve or reject a promise manually
const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback);
new Promise((resolve, reject) => { console.log('Initial'); resolve(); }) .then(() => { throw new Error('Something failed'); console.log('Do this'); }) .catch(() => { console.log('Do that'); }) .then(() => { console.log('Do this whatever happened before'); });
Promise.resolve()
and Promise.reject()
are shortcuts to manually create an already resolved or rejected promise respectively
以下两段代码均为reduce应用。用于串于执行异步或同步调用。
[func1, func2].reduce((p, f) => p.then(f), Promise.resolve());
Promise.resolve().then(func1).then(func2);
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises