如何使用一系列承诺在函数数组中传递参数 [英] How to pass parameters in an array of functions using a series of promises

查看:48
本文介绍了如何使用一系列承诺在函数数组中传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下Promises功能:

I have the following functions of Promises:

const func1 = () => new Promise((resolve, reject) => {
    console.log('func1 start');
    setTimeout(() => {
        console.log('func1 complete');
        resolve('Hello');
    }, 1000);
});

const func2 = () => new Promise((resolve, reject) => {
    console.log('func2 start');
    setTimeout(() => {
        console.log('func2 complete');
        resolve('World');
    }, 2000);
});

并依次执行这些功能,我使用:

And to execute those functions in series, I use:

const promiseSerial = funcs =>
  funcs.reduce((promise, func) =>
    promise.then(result => func().then(Array.prototype.concat.bind(result))),
    Promise.resolve([]))

并致电:

promiseSerial([func1, func2]).then(values => {
    console.log("Promise Resolved. " + values); // Promise Resolved. Hello, World
}, function(reason) {
    console.log("Promise Rejected. " + reason);
});

一切都很好,因为我可以按照函数。

And everything works fine, because I can have an array of values in series according to the order of the functions.

所以,我的问题是:

如何在函数之间传递参数?我的意思是,我想将参数从 func1 传递给 func2 。我以为也许在解决 c中,但是它不起作用。

How can I pass parameters between functions? I mean, I want to pass a parameter from func1 to func2. I have thought maybe in the resolve, but it does not works.

任何想法?

推荐答案

func2()替换

const func2 =()

const func2 =(参数)

promiseSerial()替换

promise.then(result => func()

promise.then(结果=> ; func(result [0])

console.log 参数 将向您显示字符串'Hello'

console.log the PARAMETER in func2 will show you the string 'Hello'

将参数发送到 func1 以及是否有多个 funcs

To send parameter to func1 and if you have multiple funcs

const func1 = (FIRST_PARA) => new Promise((resolve, reject) => {

  console.log('func1 start, the first parameter is ' + FIRST_PARA);
  setTimeout(() => {
    console.log('func1 complete');
    resolve('Hello');
  }, 1000);
});

const func2 = (FIRST_PARA, LAST_PARA) => new Promise((resolve, reject) => {

  console.log('func2 start, the received last parameter is ' + LAST_PARA);
  setTimeout(() => {
    console.log('func2 complete');
    resolve('World');
  }, 2000);
});

const promiseSerial = (funcs, firstParameter) => funcs.reduce((promise, func) =>
promise.then(result => func(firstParameter, result[result.length - 1]).then(Array.prototype.concat.bind(result))), Promise.resolve([]))


var firstParameter = 12;

promiseSerial([func1, func2], firstParameter).then(values => {
  console.log("Promise Resolved. " + values); // Promise Resolved. Hello, World
}, function(reason) {
  console.log("Promise Rejected. " + reason);
});

这篇关于如何使用一系列承诺在函数数组中传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆