Promise
三种状态
pending、fulfilled、rejected。只会有两种状态的变化:pending->fulfilled、pending->rejected。实际使用中用resolve、rejected表示。状态一旦改变,就不会再变。当状态变为
fulfilled/rejected,就不会再改变。无法取消Promise,一旦新建它就会立即执行,无法中途取消。
如果不设置回调函数,Promise内部抛出的错误,不会反应到外部。
当处于pending状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成)。
resolve和rejected为Promise实例化入参function的两个形参,通常以函数方传入。resolve()和rejected(),会在调用栈末尾执行。
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
// 2
// 1
-
Promise本身为立即执行,但其.then()中的方法会放到微任务队列中。
let promise = new Promise(function(resolve, reject) {
console.log('Promise');
resolve();
});
promise.then(function() {
console.log('resolved.');
});
console.log('Hi!');
// Promise
// Hi!
// resolved
Promise每一步所return的数据都会以resolve的形式传递给.then()。.then()方法返回的是一个新的Promise实例。
Catch
Promise.catch相当于 .then()没有resolve,resolve === null || resolve === undefined。
p.then((val) => console.log('fulfilled:', val))
.catch((err) => console.log('rejected', err));
// 等同于
p.then((val) => console.log('fulfilled:', val))
.then(null, (err) => console.log("rejected:", err));
一般来说,不要在
then()方法里面定义Reject状态的回调函数(即then的第二个参数),总是使用catch方法。catch()方法后还可以继续调用then()。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行会报错,因为x没有声明
resolve(x + 2);
});
};
someAsyncThing()
.catch(function(error) {
console.log('oh no', error);
})
.then(function() {
console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
// carry on
- 当然也可以继续调用
catch。
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行会报错,因为y没有声明
y + 2;
}).catch(function(error) {
console.log('carry on', error);
});
// oh no [ReferenceError: x is not defined]
// carry on [ReferenceError: y is not defined]
finally
无论Promise的结果如何,都会进入.finally(),finally与promise的状态无关。+ 本质上.finally()也是.then(),是无论成功,失败 都会处理的.then()。
all
all用于将多个promise包装成一个。
const p = Promise.all([p1, p2, p3]);
- 只有all中,所有的promise都返回成功,all才会返回成功,否则返回失败。
race
rece与all类似,但rece是其中一个成功便成功,全部失败才会返回失败。
参考阮一峰老师的es6
Generator
Generator也是一种异步解决方案。
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
var hw = helloWorldGenerator();
Generator内部使用next()调用,返回每一步的状态, 以yield分步数。
async/await
async/await为Generator的语法糖。
但async/await内置执行器,会像正常函数一样执行。
-
async/await返回的是一个promise对象,所以可以在后面写then();
async function getStockPriceByName(name) {
const symbol = await getStockSymbol(name);
const stockPrice = await getStockPrice(symbol);
return stockPrice;
}
getStockPriceByName('goog').then(function (result) {
console.log(result);
});