如何在继续执行欢迎意图 <speak> 命令之前等待此提取 JSON 请求

How to wait for this fetch JSON request before proceeding to the welcome intent <speak> command

我正在尝试使用 fetch 来获取 json 对象,并且它确实可以正常工作。然后我根据数据分配一个字符串,并想在 ssml 响应中使用该字符串......按照我现在的方式进行操作,如果我尝试放置,它太慢了大约 300 毫秒并且 var 未定义此代码中其他地方的 ssml 响应出现错误 "No response has been set"。谁能给我指出正确的方向,我已经连续 5 天都在处理这个问题了(已经放弃使用 Firestore 进行数据检索,因为每次都需要 30 秒以上的时间)。

//this is what I have in the Welcome Intent -- I should note that all of this 
//is in a function called welcome() which is called by the welcome intent

function foo() {
  // RETURN the promise
  return fetch("https://webhostapp.com/townsheriff.json")
    .then(function(response){
      return response.json(); // process it inside the `then`
    });
}

foo().then(function(response){
  // access the value inside the `then`
  currentquestion = response[2].n111.toString(); //assigning variable works

  //I tried putting the ssml response here but then got "no response set"
  //error

})


//here it comes up as undefined because it happens 300ms too early
const ssml =
  '<speak>' +
    '<audiosrc="https://test.mp3">You have just been made sheriff...</audio>'+
    currentquestion  +
  '</speak>';

conv.ask(ssml);

问题是,您想要对 fetch 调用的 API 结果执行的所有操作 都需要作为 Promise 的一部分进行处理解析度。 Promises 的工作方式是,它之后的代码会在最初 运行 时继续执行,但是 then() 块中的内容将在 Promise 完成时被调用。

此外,您还需要确保 return Promise,以便 Intent Handler 调度程序知道等待 Promise 完成。

第一部分是通过将所有内容(包括对 conv.ask() 的调用)放在 then() 部分来处理的。第二部分由 returning Promise 处理。它可能看起来像这样:

// Make sure you return this promise
return foo().then(function(response){
  // access the value inside the `then`
  currentquestion = response[2].n111.toString(); //assigning variable works

  // Make sure you build the response, and ask it inside the promise resolution
  const ssml =
    '<speak>' +
    '<audiosrc="https://test.mp3">You have just been made sheriff...</audio>'+
    currentquestion  +
    '</speak>';

  conv.ask(ssml);
});