首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在进入欢迎意图<speak>命令之前等待此fetch JSON请求

如何在进入欢迎意图<speak>命令之前等待此fetch JSON请求
EN

Stack Overflow用户
提问于 2019-06-05 03:42:49
回答 1查看 30关注 0票数 1

我正在尝试使用fetch来获取一个json对象,这确实可以正常工作。然后我根据数据分配一个字符串,并想在ssml响应中使用它现在的方式,它大约太慢了300ms,并且变量是未定义的,如果我试图将ssml响应放在这段代码的其他地方,它会出现错误"No response response...doing response...doing“。有人能给我指出正确的方向吗,我已经连续5天在这个问题上了(我已经放弃了Firestore的数据检索,因为它每次都要花费30+秒)。

代码语言:javascript
复制
//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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-05 03:54:51

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

此外,您还需要确保返回promise,以便Intent Handler dispatcher知道要等待Promise完成。

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

代码语言:javascript
复制
// 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);
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56450332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档