建立网站要多少钱一年,做网站从什么做起,数据分析系统搭建,福州手游网站建设目录 前言
for使用await -- 有效的
forEach使用await -- 无效的
for of 使用await 有效的
for await of 使用await 有效的
总结 前言
在JavaScript的forEach方法中使用await是无效的#xff0c;因为forEach方法不支持异步操作的等待。 forEach是一个数组的遍历方法forEach方法中使用await是无效的因为forEach方法不支持异步操作的等待。 forEach是一个数组的遍历方法它会对数组中的每个元素依次执行提供的回调函数。而在JavaScript中await关键字只能在异步函数(async函数)中使用用于等待一个Promise对象的解析结果。
在forEach的回调函数中使用await关键字实际上会导致它被忽略无法正确地等待异步操作的完成。这是因为forEach不会等待回调函数中的异步操作完成而是立即执行下一个回调函数。 如果你需要在数组的每个元素上执行异步操作并等待每个操作完成可以考虑使用for...of循环结合await关键字或者使用map方法结合Promise.all方法来处理异步操作。 Promise.all() 方法不能保证 Promise 对象的执行顺序它只能确保所有的 Promise 对象都被解析后才会触发后续的处理。 虽然 Promise.all() 方法会等待所有的 Promise 对象都被解析但它并不能保证上传操作的顺序。上传操作的顺序是可能会受到网络延迟等因素的影响导致后续的处理可能会在某些上传操作完成之前就开始执行。 但是Promise.all()所以异步成功后返回的数组是对应关系 如果你希望确保上传操作按照数组中的顺序执行可以考虑使用 for...of 循环并等待每个上传操作完成后再处理下一个元素。 注意
for要使用在async异步方法里循环会等await执行而停留await是有效的有breakforEach没有break循环不会等await执行而停留await是无效的for of要使用在async异步方法里执行期间await之前的代码会执行到了await会等待await执行完才继续往下执行有breakfor await of也要用在async异步方法里有break但是它一般是使用在item是个异步方法的情况下并不常见场景如下面对应的例子要遍历的数组元素是个异步请求异步没回来之前整个for循环代码不执行。
for使用await -- 有效的
scriptlet arr [我, 爱, 编, 程]function getDatas(e) {return axios.get(https://api.oioweb.cn/api/txt/dict?text${e})}async function execute() {for (let i 0; i arr.length; i) {console.log(第${i 1}次${arr[i]}执行了)let datas await getDatas(arr[i])console.log(返回结果 datas.data.result.words)console.log(第${i 1}次${arr[i]}执行完了)console.log(---------end--------------)}}execute()/script forEach使用await -- 无效的
scriptlet arr [我, 爱, 编, 程]function getDatas(e) {return axios.get(https://api.oioweb.cn/api/txt/dict?text${e})}async function execute() {arr.forEach(async (item, index) {console.log(第${index 1}次${item}执行了)let datas await getDatas(item)console.log(返回结果 datas.data.result.words)console.log(第${index}次${item}执行完了)console.log(---------end--------------)})}execute()/script
可以看到forEach中使用await是无效的只不过await后面的代码能按顺序执行
for of 使用await 有效的
scriptlet arr [我, 爱, 编, 程]function getDatas(e) {return axios.get(https://api.oioweb.cn/api/txt/dict?text${e})}async function execute() {let index 0for (const item of arr) {console.log(第${index 1}次${item}执行了)let datas await getDatas(item)console.log(返回结果 datas.data.result.words)console.log(第${index 1}次${item}执行完了)console.log(---------end--------------)index 1}}execute()/script for await of 使用await 有效的
scriptfunction getDatas(e) {return axios.get(https://api.oioweb.cn/api/txt/dict?text${e})}let arr [getDatas(我), getDatas(爱), getDatas(编), getDatas(程)]async function execute() {let index 0for await (const item of arr) {console.log(第${index 1}次方法${index 1}执行了)console.log(返回结果 item.data.result.words)console.log(第${index 1}次方法${index 1}执行完了)console.log(---------end--------------)index 1}}execute()/script总结 实际开发中我们可以发现其实for、while、for in、for of、for await of使用await都是生效的而几乎有回调的遍历方法forEach、map、filter、reduce、some、every、find等使用await都是不生效的