Javascript 承诺的创造是同步的吗?
我需要编写一个函数来进行两次链接HTTP调用,并在第二次调用的结果可用时对结果进行操作 我认为有效的方法是 函数getdata(){ 返回获取('https://jsonplaceholder.typicode.com/todos/1') .then(r=>r.json()) .然后(r=>fetch(`https://jsonplaceholder.typicode.com/todos/2`) .然后(s=>s.json()) ) } 设m=getdata()Javascript 承诺的创造是同步的吗?,javascript,promise,Javascript,Promise,我需要编写一个函数来进行两次链接HTTP调用,并在第二次调用的结果可用时对结果进行操作 我认为有效的方法是 函数getdata(){ 返回获取('https://jsonplaceholder.typicode.com/todos/1') .then(r=>r.json()) .然后(r=>fetch(`https://jsonplaceholder.typicode.com/todos/2`) .然后(s=>s.json()) ) } 设m=getdata() m、 然后(x=>consol
m、 然后(x=>console.log(JSON.stringify(x))问题在于,在Nested
fetch
中有一个承诺没有与外部承诺链接,即s.JSON()
:
将
s.json()。总之,一般来说,promise回调中的代码是在promise解析之后调用的谢谢。在这种情况下,为什么第一个代码按预期工作?因为内部.json
由arrow函数(隐式)返回。(第二段代码中带有块{
}
的箭头函数不会隐式返回任何内容,因此您需要返回
语句)我理解,谢谢。我还发现,我最好(至少从个人可读性的角度来看)直接链接then()
调用。
.then(s => {
console.log(s)
s.json() // <---- This is not being returned; the Promise chain will resolve to undefined
})