我不知道如何返回嵌套的.then方法,并将值解析为调用它的函数?
我可以在最后一个.then()
的最深处打印它,但是我想在事件监听器中打印返回的值。
connectedCallback () {
this.input.addEventListener('input', event => {
this.search(this.input.value)
})
}
search (str) {
let searchResult = window.fetch(`http://localhost:3000/api/?q=${str}`)
.then(result => {
return result.json()
.then(result => {
return result
})
})
}
}
答案 0 :(得分:2)
使用async / await等待事件侦听器中的promise结果。您还可以大大简化您的诺言链:
connectedCallback() {
this.input.addEventListener("input", async event => {
const result = await this.search(this.input.value);
console.log(result);
});
},
search(str) {
return window
.fetch(`http://localhost:3000/api/?q=${str}`)
.then(result => result.json());
}
我建议阅读诺言并熟悉它们的工作方式。