如何将 returns 承诺的函数推送到接受参数的数组
How to push a function that returns a promise to an array, which accepts params
所以我进行了一堆 mysql 调用,我希望通过将逻辑分离到它们自己的函数和我自己的函数中来使代码更简洁、更可重用想要做的是,因为调用的数量总是会增长,所以构建一个 promise 数组并通过 Promise.all
执行它们。我已经熟悉这个概念,但通常我的做法是这样的:
const promiseChain = []
array.forEach(item => promiseChain.push(new Promise((resolve, reject) { ... logic });
或类似的东西。但我不能放弃这样做,因为我想分离出所有的逻辑,所以现在我有一堆不同的功能,所有 returning 承诺。我对现在可以使用什么语法将函数添加到数组而不实际调用它们感到有点困惑。我确实看到了一个 SO 答案,它指定了这样的内容:
const array = [func1, func2]
虽然我认为这行不通,但我的函数都有不同的参数。有没有一种好的、干净的方法可以将 return 承诺的函数添加到也接收参数的数组(显然不执行它们)?或者它只是像这样:
promiseChain.push(new Promise((resolve, reject) => {
functionPromise(params).then(() => resolve()).catch(err => reject(err))
})
我想我想问的是,是否有比上述方法更好的方法?由于这些功能已经 return 承诺,所以看起来代码比必要的多。好像矫枉过正了。
is there a better way to do it then the above?
您的示例相当于:
promiseChain.push(functionPromise(params));
Is there a good, clean way to add functions that return promises to an array (obviously without executing them) that also receive parameters
要添加函数而不执行它们:
array.push(functionPromise);
参数可以绑定到数组中的函数:
array.push(funcitonPromise.bind(funcitonPromise, ...params))
之后可以通过以下方式调用它们:
await Promise.all(array.map(func => func()));
所以我进行了一堆 mysql 调用,我希望通过将逻辑分离到它们自己的函数和我自己的函数中来使代码更简洁、更可重用想要做的是,因为调用的数量总是会增长,所以构建一个 promise 数组并通过 Promise.all
执行它们。我已经熟悉这个概念,但通常我的做法是这样的:
const promiseChain = []
array.forEach(item => promiseChain.push(new Promise((resolve, reject) { ... logic });
或类似的东西。但我不能放弃这样做,因为我想分离出所有的逻辑,所以现在我有一堆不同的功能,所有 returning 承诺。我对现在可以使用什么语法将函数添加到数组而不实际调用它们感到有点困惑。我确实看到了一个 SO 答案,它指定了这样的内容:
const array = [func1, func2]
虽然我认为这行不通,但我的函数都有不同的参数。有没有一种好的、干净的方法可以将 return 承诺的函数添加到也接收参数的数组(显然不执行它们)?或者它只是像这样:
promiseChain.push(new Promise((resolve, reject) => {
functionPromise(params).then(() => resolve()).catch(err => reject(err))
})
我想我想问的是,是否有比上述方法更好的方法?由于这些功能已经 return 承诺,所以看起来代码比必要的多。好像矫枉过正了。
is there a better way to do it then the above?
您的示例相当于:
promiseChain.push(functionPromise(params));
Is there a good, clean way to add functions that return promises to an array (obviously without executing them) that also receive parameters
要添加函数而不执行它们:
array.push(functionPromise);
参数可以绑定到数组中的函数:
array.push(funcitonPromise.bind(funcitonPromise, ...params))
之后可以通过以下方式调用它们:
await Promise.all(array.map(func => func()));