简体   繁体   English

如何从ES6承诺中获取原始数组

[英]How to get Primitive Array from ES6 Promises

I am trying to load glsl scripts as strings using the ES6 Promise and Fetch APIs. 我正在尝试使用ES6 Promise和Fetch API将glsl脚本作为字符串加载。 I thought I had a pretty elegant solution for getting the vertex and fragment shaders and creating a new programInfo with twgl.js 我以为我有一个非常优雅的解决方案,用于获取顶点和片段着色器并使用twgl.js创建新的programInfo

Promise.all([fetch(vert_url),fetch(frag_url))])
       .then((responses) => responses.map((response) => response.text()))
       .then((sources) => this.programInfo = twgl.createProgramInfo(gl, sources));

The problem is that it seems that response.text() is returning a Promise rather than a raw string. 问题在于,似乎response.text()返回的是Promise而不是原始字符串。 Inside twgl.createProgramInfo() it runs sources through a map, and then attempts to run indexOf on the results. 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) {
      ...

Chrome throws a javascript error on the final line there: Chrome在该行的最后一行抛出javascript错误:

Uncaught (in promise) TypeError: source.indexOf is not a function

I can't seem to figure out how to turn sources into real strings. 我似乎无法弄清楚如何将sources变成真正的字符串。 Anybody have an idea how to get this working? 有人知道如何使它工作吗?

Note : This is actually in a React app created using create-react-app , that means webpack and babel are being used to transpile this from jsx. 注意 :这实际上是在使用create-react-app创建的React应用程序中 ,这意味着将使用webpack和babel从jsx进行转换。

In order to convert an array of promises into a promise of an array, use Promise.all : 为了将一个promise数组转换为一个数组的promise,请使用Promise.all

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#then will evaluate the promise you return in the callback from Promise.all , and will make the next call to .then evaluate to the array of sources, which is what your code expects. Promise#then将评估您在Promise.all的回调中返回的诺言,并将对Promise.all进行下一次调用.then评估源数组,这是您的代码所期望的。


With a promise library like Bluebird , you can use Promise.map in order to make this more readable. 使用诸如Bluebird的 Promise.map库,您可以使用Promise.map使其更具可读性。

Promise.all([fetch(vert_url), fetch(frag_url)])
       .map(response => response.text())
       .then(sources => this.programInfo = twgl.createProgramInfo(gl, sources));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM