温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ES6中Promise、async和await面试题实例代码分析

发布时间:2023-02-22 10:03:31 来源:亿速云 阅读:69 作者:iii 栏目:开发技术

这篇“ES6中Promise、async和await面试题实例代码分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“ES6中Promise、async和await面试题实例代码分析”文章吧。

知识点:

  • JS 执行顺序:单线程,自上而下、先同步后异步、先微任务后宏任务

  • new promise() -> Promise.resolve(),触发then

  • new promise((reject)=>{reject()}) -> promise.reject(),触发catch

  • then 和 catch 内部没有 throw new Error 相当于 resolve

  • async function 相当于返回 Promise.resolve()

  • await 后面的代码都是异步的,微任务;setTimeout是宏任务

  • 初始化Promise时,函数内部代码会被立即执行

代码:

考点1:Promise.resolve、Promise.reject执行顺序

Promise.resolve().then(() => {  // 优先寻找then
		console.log(1);
	}).catch(() => {
		console.log(2);
	})
	// 1
Promise.reject().then(() => {  // 优先寻找catch
		console.log(1);
	}).catch(() => {
		console.log(2);
	})
	// 2

考点2:then 和 catch 内部没有 throw new Error() 相当于 resolve

Promise.resolve().then(() => {
		console.log(1);
	}).catch(() => {
		console.log(2);
	}).then(() => {
		console.log(3);
	})
	// 1 3
Promise.reject().then(() => {
		console.log(1);
	}).catch(() => {
		console.log(2);
	}).then(() => {
		console.log(3);
	})
	// 2 3
Promise.reject().then(() => {
		console.log(1);
	}).catch(() => {
		console.log(2);
		throw new Error();
	}).then(() => {
		console.log(3);
	})
	// 2 报错
Promise.reject().then(() => {
		console.log(1);
	}).catch(() => {
		console.log(2);
		throw new Error();
	}).then(() => {
		console.log(3);
	}).catch(() => {
		console.log(4);
	})
	// 2 4

考点3:async function -> 相当于返回一个 Promise.resolve

const res = async function fn() {
	return 100;
}
console.log(res());  // 返回一个resolve状态的Promise对象 Promise {<fulfilled>: 100}
res().then(()=>{
	console.log(0);
}).catch(()=>{
	console.log(1);
})
// 0

(async function () {
	const a = fn();
	const b = await fn();
	console.log(a);  // Promise {<fulfilled>: 100}
	console.log(b);  // 100
})()

考点4: await 代码执行顺序

async function fn1() {
	console.log("fn1 start");
	await fn2();
	console.log("fn1 end");
}
async function fn2() {
	console.log("fn2 start");
}
console.log("start");
fn1();
console.log("end");
/**
 * 打印顺序:
 * start
 * fn1 start
 * fn2 start
 * end
 * fn1 end
 */
async function fn1() {
	console.log("fn1 start");
	await fn2();
	console.log("fn1 end");
	await fn3();
	console.log("fn3 end");
}
async function fn2() {
	console.log("fn2");
}
async function fn3() {
	console.log("fn3");
}
console.log("start");
fn1();
console.log("end");
/**
 * 打印顺序:
 * start
 * fn1 start
 * fn2
 * end
 * fn1 end
 * fn3
 * fn3 end
 */

考点5:Promise 与 setTimeout 执行顺序

console.log("start");
setTimeout(()=>{
	console.log("setTimeout")
});
Promise.resolve().then(()=>{
	console.log("Promise")
})
console.log("end")
/**
 * 打印顺序:
 * start
 * end
 * Promise
 * setTimeout
 */
async function fn1() {
	console.log("fn1 start");
	await fn2();
	console.log("fn1 end");  // await后面的代码为"微任务代码"
}
async function fn2() {
	console.log("fn2");
}
console.log("start");
setTimeout(()=>{
	console.log("setTimeout");  // 宏任务 
});
fn1();
console.log("end");
/**
 * 打印顺序:
 * start
 * fn1 start
 * fn2
 * end
 * fn1 end
 * setTimeout
 */

附:promise与async await结合使用

昨天看了一道字节外包的面试题

 const list = [1, 2, 3];
    const square = num => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(num * num);
            }, 1000);
        });
    }
    function test() {
        // 修改这里的代码
        list.forEach(async x => {
            const res = await square(x);
            console.log(res);
        });
    }
    test()

需要修改的是把同步执行的数组替换成换成异步打印。

在测试以后我们可以-验证,forEach和for循环不同的是for循环可以修改数组的值,且forEach取不到具体某一项的值,这里的异步说的是每执行一次数组循环,就执行一步test()方法,

const list = [1, 2, 3];
const square = num => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(num * num);
        }, 1000);
    });
}
 function test() {
  for(let x of list) {
    var res = await square(x)
    console.log(res)
  }
}
test()

以上就是关于“ES6中Promise、async和await面试题实例代码分析”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI