我正在尝试使用fetch来获取一个json对象,这确实可以正常工作。然后我根据数据分配一个字符串,并想在ssml响应中使用它现在的方式,它大约太慢了300ms,并且变量是未定义的,如果我试图将ssml响应放在这段代码的其他地方,它会出现错误"No response response...doing response...doing“。有人能给我指出正确的方向吗,我已经连续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);
发布于 2019-06-05 03:54:51
问题是,您希望对fetch
的API调用结果执行的所有操作都需要作为Promise解析的一部分进行处理。Promise的工作方式是,它之后的代码在最初运行时将继续执行,但当Promise完成时,将调用then()
块中的内容。
此外,您还需要确保返回promise,以便Intent Handler dispatcher知道要等待Promise完成。
第一部分通过将所有内容都放入then()
部分来处理,包括对conv.ask()
的调用。第二部分通过返回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);
});
https://stackoverflow.com/questions/56450332
复制相似问题