栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

循环原生承诺;

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

循环原生承诺;

我见过的任何带有promise循环的辅助函数实际上使它变得比您可以使用递归开箱即用的方法差很多。

是的,

.thenReturn
但是更好一点:

function readFile(index) {    return new Promise(function(resolve) {        setTimeout(function() { console.log("Read file number " + (index +1)); resolve();        }, 500);    });}// The loop initializationPromise.resolve(0).then(function loop(i) {    // The loop check    if (i < len) {   // The post iteration increment        return readFile(i).thenReturn(i + 1).then(loop);    }}).then(function() {    console.log("done");}).catch(function(e) {    console.log("error", e);});

在jsfiddle中查看http://jsfiddle.net/fd1wc1ra/

这几乎等同于:

try {    for (var i = 0; i < len; ++i) {        readFile(i);    }    console.log("done");} catch (e) {    console.log("error", e);}

如果要进行嵌套循环,则完全相同:

http://jsfiddle.net/fd1wc1ra/1/

function printItem(item) {    return new Promise(function(resolve) {        setTimeout(function() { console.log("Item " + item); resolve();        }, 500);    });}var mdArray = [[1,2], [3,4], [5,6]];Promise.resolve(0).then(function loop(i) {    if (i < mdArray.length) {        var array = mdArray[i];        return Promise.resolve(0).then(function innerLoop(j) { if (j < array.length) {     var item = array[j];     return printItem(item).thenReturn(j + 1).then(innerLoop); }        }).thenReturn(i + 1).then(loop);    }}).then(function() {    console.log("done");}).catch(function(e) {    console.log("error", e);});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469218.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号