Promise
promise是异步编程的一种解决方案,他比传统的回调函数加事件更加合理和强大,我用promise除了使用他的异步操作外,还使用promise在项目中解决了回调地狱等问题。
promise的特点,promise一共有两个特点:
对象不受外界影响,一共有三个状态,分别是进行中,成功,或者失败,只有异步操作的结果,可以决定是哪一种状态,任何其他的操作都无法改变这个状态一旦状态改变,就不会再变,任何时候都可以得到这个结果,promise的状态改变只有两种可能,要么是成功,要么失败。
Promise解决回调地狱:
var sayhello = function (order) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log(order);
//在异步操作执行完后执行 resolve() 函数
resolve();
}, 1000);
});
}
sayhello("first").then(function () {
//仍然返回一个 Promise 对象
return sayhello("second");
}).then(function () {
return sayhello("third");
}).then(function () {
console.log('end');
}).catch(function (err) {
console.log(err);
})
//输出:first second third end
promise基本用法
ES6规定,Promise对象是一个构造函数,用来生成Promise实例
const promist = new Promise(function(resolve,reject){
if(/*异步操作成功*/){
resolve(value);
}else{
reject(error);
}
})
Promise 实例生成以后,可以用then 方法分别指定resolved状态和rejected状态的回调函数。
promise.then(function(value){
//success
},function(error){
//failure
});
async 和 await是什么
async 是“异步”的简写, async 用于声明一个异步的 function
await 可以认为是 async wait 的简写,await 用于等待一个异步方法执行完成。
特点:
asayc的用法,它作为一个关键字放到函数前面,这样普通函数就变为了异步函数
异步async函数调用,跟普通函数的使用方式一样
异步async函数返回一个promise对象
async函数配合await关键字使用是异步方法,但是阻塞式的
例 :
async function testAsync() {
const response = await new Promise((resolve, reject) => {
setTimeout(resolve("this is async"),2000);
});
console.log(response);
};
testAsync();
async、await串行并行处理
串行:等待前面一个await执行后接着执行下一个await,以此类推
async function fun1() {
return new Promise((resolve, reject) => {
setTimeout(resolve,3000);
});
};
async function test(){
console.log('开始执行', new Date().toString());
await fun1();
console.log('结束执行', new Date().toString());
}
并行:将多个promise直接发起请求(先执行async所在函数),然后再进行await操作。
async function asyncAwait(str) {
return await new Promise((resolve) => {
setTimeout(resolve(str), 1000);
})
}
const parallel = async () => { //并行执行
console.time('parallel')
const parallel1 = asyncAwait('async1');
const parallel2 = asyncAwait('async2')
//直接打印
console.log(await parallel1)
console.log(await parallel2)
console.timeEnd('parallel');
};
parallel();