试图理解D3 js的Promise实现的不同步骤。
有两个输入文件并承诺全部:
Promise.all([jsonFile, txtFile]).then(input)
数组已合并为一个单独的输入,可以称为一个单参数函数,如:
function input(data) {
console.log(data[0]) // json
console.log(data[1]) // txt
}
想象一下,我想将第二个函数实现为具有两个输入(如function input(json, txt)
)的两个参数。then()
语句中应该发生什么才能使代码执行此操作?
感谢
如果您想用两个参数实现input
功能:
function input(json, txt) {
// omitted
}
然后你可以使用休息参数〔更多〕:
Promise.all([jsonFile, txtFile])
.then((data) => input(...data))
或者你可以更明确一点:
Promise.all([jsonFile, txtFile])
.then(([json, txt]) => input(json, txt))
您的问题只是关于Promise.all
行为
文档说明您有正确的期望,并且承诺的顺序在解决时得到保留:
无论完成顺序如何,返回的值都将按照传递的Promises的顺序。
const promises = [Promise.resolve(1), Promise.resolve('some text')]
const processInputCallback = console.log
Promise.all(promises).then(processInputCallback)
也许这里唯一需要补充的是,如果任何一个承诺被拒绝,它都会在不等待所有承诺得到解决的情况下失败。