如何使用一系列承诺在函数数组中传递参数

如何使用一系列承诺在函数数组中传递参数

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

问题描述

我具有以下Promises功能:

I have the following functions of Promises:

 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);
});

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

07-17 20:59