这两页,就可以厘清之前混沌的代码思路。
其实,这几种都用过,只是不能系统的讲出这些关系。。
现在的理解是:
var promise = new Promise(function(resolve, reject) { // 异步处理 // 处理结束后、调用resolve 或 reject });
这个过程,有可能需要自己构建,也可能是vue或jquery的api返回。
function asyncFunction() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve('Async Hello world'); }, 16); }); }
promise.then(onFulfilled, onRejected)
这个可能有另外两个相同的实现:(就是then后要么带两个函数,要么then带一个函数,catch带一个函数)
1,分开正确和错误
asyncFunction().then(function (value) { console.log(value); // => 'Async Hello world' }).catch(function (error) { console.log(error); });
2,混和正确和错误。
asyncFunction().then(function (value) { console.log(value); }, function (error) { console.log(error); });
promise.then
成功和失败时都可以使用。 另外在只想对异常进行处理时可以采用 promise.then(undefined, onRejected)
这种方式,只指定reject时的回调函数即可。 不过这种情况下 promise.catch(onRejected)
应该是个更好的选择。
http://liubin.org/promises-book/