Javascript 如何从ES6中获取基元数组
我正在尝试使用ES6 Promise和Fetch API将glsl脚本作为字符串加载。我认为我有一个非常优雅的解决方案来获取顶点和片段着色器,并使用twgl.js创建一个新的programInfoJavascript 如何从ES6中获取基元数组,javascript,reactjs,es6-promise,twgl.js,Javascript,Reactjs,Es6 Promise,Twgl.js,我正在尝试使用ES6 Promise和Fetch API将glsl脚本作为字符串加载。我认为我有一个非常优雅的解决方案来获取顶点和片段着色器,并使用twgl.js创建一个新的programInfo Promise.all([fetch(vert_url),fetch(frag_url))]) .then((responses) => responses.map((response) => response.text())) .then((sources)
Promise.all([fetch(vert_url),fetch(frag_url))])
.then((responses) => responses.map((response) => response.text()))
.then((sources) => this.programInfo = twgl.createProgramInfo(gl, sources));
问题是response.text()似乎返回的是承诺,而不是原始字符串。在twgl.createProgramInfo()内部,它通过映射运行源代码,然后尝试对结果运行indexOf
function createProgramInfo(gl, shaderSources, ...) {
...
shaderSources = shaderSources.map(function (source) {
// Lets assume if there is no \n it's an id
if (source.indexOf("\n") < 0) {
...
我似乎不知道如何将源代码
转换成真正的字符串。有人知道如何让它工作吗
注意:这实际上是在使用创建React应用程序创建的React应用程序中,这意味着正在使用webpack和babel从jsx传输此信息。要将承诺数组转换为数组承诺,请使用:
将计算从promise.all
在回调中返回的承诺,并将下一次调用。然后
计算源数组,这是代码所期望的
有了这样的promise库,您可以使用它来提高可读性
Promise.all([fetch(vert_url), fetch(frag_url)])
.map(response => response.text())
.then(sources => this.programInfo = twgl.createProgramInfo(gl, sources));
@ 4CARS可能会考虑把你的评论变成答案,所以这个线程可以closed@4castle的答案是正确的,但是从实现的角度来看,为什么不将then
s组合起来呢?因为第一个没有做任何异步行为?@Damon如果他们不使用两个then
调用,他们将以嵌套回调结束,这在承诺中是不必要的。@4卡斯特怎么会这样?您只需在第一个中将映射传递到createProgramInfo
,然后再传递到中,类似于this.programInfo=twgl.createProgramInfo(gl,responses.map(=>.text())
),因为提示同步映射没有意义。@Damon根据OP,.text()
返回承诺,不是函数期望的实际字符串,因此必须有另一个。然后
等待这些承诺。很好,从未听说过这种技术,但也可以使用参数
,而不需要额外的承诺?看起来有点像滥用承诺。@JuanMendes也许你应该发布你自己的答案?这段代码非常简单(这不是什么特殊的技术),但是如果你知道另一种方法,请分享。
Promise.all([fetch(vert_url), fetch(frag_url)])
.then(responses => Promise.all(responses.map(response => response.text())))
.then(sources => this.programInfo = twgl.createProgramInfo(gl, sources));
Promise.all([fetch(vert_url), fetch(frag_url)])
.map(response => response.text())
.then(sources => this.programInfo = twgl.createProgramInfo(gl, sources));