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

ε祈祈猫儿з 提交于 2019-12-24 08:24:28

问题


I'm trying to use fetch to get a json object, and this does work correctly. Then I'm assigning a string based on the data and want to use that string in the ssml response...doing it the way I have it now it is about 300 ms too slow and the var is undefined, if I try to place the ssml response elsewhere in this code it comes up with an error "No response has been set". Can anyone point me in the right direction, I've literally been on this issue for 5 days in a row (already gave up on Firestore for data retrieval as it was taking 30+ seconds each time anyway).

//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);

回答1:


The issue is that everything you want to do with the result of your API call with fetch needs to be handled as part of the Promise resolution. The way Promises work is that code after it will continue to be executed when it is initially run, but what is in the then() block will be called when the Promise completes.

Additionally, you need to make sure you return the promise as well, so the Intent Handler dispatcher knows to wait for the Promise to complete.

The first part is handled by putting everything, including the call to conv.ask() in the then() portion. The second part is handled by returning the Promise. It might look something like this:

// 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);
});


来源:https://stackoverflow.com/questions/56450332/how-to-wait-for-this-fetch-json-request-before-proceeding-to-the-welcome-intent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!