如何从 ES6 Promises 获取原始数组

How to get Primitive Array from ES6 Promises

我正在尝试使用 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) => this.programInfo = twgl.createProgramInfo(gl, sources));

问题是 response.text() 似乎返回的是 Promise 而不是原始字符串。在 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 在最后一行抛出 javascript 错误:

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

我似乎无法弄清楚如何将 sources 变成真正的字符串。有人知道如何让它工作吗?

注意: 这实际上是在使用 create-react-app 创建的 React 应用程序中,这意味着正在使用 webpack 和 babel从 jsx 转译这个。

为了将承诺数组转换为数组承诺,请使用 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 将在 Promise.all 的回调中评估您 return 的承诺,并将对 .then 的下一次调用评估源数组,这是您的代码所期望的。


使用像 Bluebird, you can use Promise.map 这样的 promise 库来提高可读性。

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