Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Asynchronous Serial execution in Promise

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

本篇文章为大家展示了Promise中怎么实现异步串行执行,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

按照要求:

实现 mergePromise 函数,把传进去的函数数组按顺序先后执行,并且把返回的数据先后放到数组 data 中。

代码如下:

const timeout = ms => new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, ms);});

const ajax1 = () => timeout(2000).then(() => { console.log('1'); return 1;});

const ajax2 = () => timeout(1000).then(() => { console.log('2'); return 2;});

const ajax3 = () => timeout(2000).then(() => { console.log('3'); return 3;});

const mergePromise = ajaxArray => { // 在这里实现你的代码

};

mergePromise([ajax1, ajax2, ajax3]).then(data => { console.log('done'); console.log(data); // data 为 [1, 2, 3]});

// 要求分别输出// 1// 2// 3// done// [1, 2, 3]

分析:

timeout是一个函数,这个函数执行后返回一个promise实例。

ajax1 、ajax2、ajax3 都是函数,不过这些函数有一些特点,执行后都会会返回一个 新的promise实例。

按题目的要求我们只要顺序执行这三个函数就好了,然后把结果放到 data 中,但是这些函数里都是异步操作,想要按顺序执行,然后输出 1,2,3并没有那么简单,看个例子。

function A() { setTimeout(function () { console.log('a'); }, 3000);}

function B() { setTimeout(function () { console.log('b'); }, 1000);}

A();B();

// b// a

例子中我们是按顺序执行的 A,B 但是输出的结果却是 b,a 对于这些异步函数来说,并不会按顺序执行完一个,再执行后一个。

这道题主要考察的是Promise 控制异步流程,我们要想办法,让这些函数,一个执行完之后,再执行下一个,代码如何实现呢?

// 保存数组中的函数执行后的结果var data = [];

// Promise.resolve方法调用时不带参数,直接返回一个resolved状态的 Promise 对象。var sequence = Promise.resolve();

ajaxArray.forEach(function (item) { // 第一次的 then 方法用来执行数组中的每个函数, // 第二次的 then 方法接受数组中的函数执行后返回的结果, // 并把结果添加到 data 中,然后把 data 返回。 sequence = sequence.then(item).then(function (res) { data.push(res); return data; });})

// 遍历结束后,返回一个 Promise,也就是 sequence, 他的 [[PromiseValue]] 值就是 data,// 而 data(保存数组中的函数执行后的结果) 也会作为参数,传入下次调用的 then 方法中。return sequence;

大概思路如下:全局定义一个promise实例sequence,循环遍历函数数组,每次循环更新sequence,将要执行的函数item通过sequence的then方法进行串联,并且将执行结果推入data数组,最后将更新的data返回,这样保证后面sequence调用then方法,如何后面的函数需要使用data只需要将函数改为带参数的函数。

上述内容就是Promise中怎么实现异步串行执行,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report