Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - 如何在javascript中使用reduce函数在promise内调用函数(How to call a function inside a promise with reduce function in javascript)

Here is my array(这是我的数组)

arr = [2,3,4] here is my functions(这是我的职能) function functionMultpily(p1, p2) { return( p1 * p2); } function functionADD(p1, p2) { return( p1 + p2); } I need to use this functions in a promise such that it should complete one after another by taking the values from arr by using Reduce function.(我需要在promise中使用此函数,以便它应该通过使用Reduce函数从arr中获取值来一个接一个地完成。)   ask by Mar1009 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use Promise.resolve() along with Promise.prototype.then() as follows:(您可以将Promise.resolve()Promise.prototype.then()一起使用,如下所示:)

const arr = [1, 2, 3, 4, 5, 6]; const sleep = ms => new Promise(res => setTimeout(res, ms)); const add = (a, b) => sleep(500).then(() => a + b); const multiply = (a, b) => sleep(500).then(() => a * b); arr .reduce((p, x) => p.then((y) => add(x, y)), Promise.resolve(0)) .then(sum => console.log(sum)); arr .reduce((p, x) => p.then((y) => multiply(x, y)), Promise.resolve(1)) .then(product => console.log(product));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...