【问题标题】:Issue with promise chain承诺链问题
【发布时间】:2020-04-15 23:51:58
【问题描述】:
import { Observable } from 'rxjs/internal/Observable';

export function createHttpObservable(url: string) {
    console.log('Url is', url);
    return Observable.create(observer => {
        fetch(url)
        .then(response => {
            console.log(response);
            console.log(response.json());
            return response.json();
        })
        .then(body => {
            observer.next(body);
            observer.complete();
        })
        .catch(err => observer.error(err));
    });
}

我无法弄清楚为什么在上面的代码中执行没有移动到第二个然后阻塞。浏览器控制台日志如下。

但是,如果我删除 console.log(response.json()); 行,代码可以正常工作。可能这是一个非常基本的问题,但不知何故我无法弄清楚。如果你知道,请帮助我。提前致谢。

【问题讨论】:

  • response.json() 是一个承诺,你为什么还要记录它?
  • 如果你想调试这个,我会先设置const resp = response.json();,然后再设置console.log(resp); return resp。我找不到文档,但我相信 response.json() 解决了这个承诺(仔细检查),这就是为什么第二个 then 语句没有用你给定的代码执行。
  • 您是在问为什么 console.log 会破坏代码,或者如何解决这个问题? B/c 'response.json()' 返回一个承诺的事实并不是代码中断的真正原因。
  • 如果你使用 Angular,为什么不使用Angular's HTTP

标签: angular typescript promise rxjs


【解决方案1】:

Response#bodyReadableStream。一个流只能被消费一次,然后它就是空的。自从Body#json() 方法reads the stream to completion 以来,您第二次尝试使用相同的主体时,您将进入一个空流。这就是Response API 实现锁定流并且不允许调用该方法两次的原因。

你可以自己试试:

const a = new ReadableStream();
const b = new Response(a);

b.json(); // returns a Promise
b.json(); // TypeError: Failed to execute 'json' on 'Response': body stream is locked

【讨论】:

  • 不客气。如果这回答了您的问题,您可以将其标记为答案。您的问题将被标记为已回答。
【解决方案2】:

调用response.json() 会锁定资源,因此第二次调用将失败。

您应该避免调用它两次,但如果您真的想在那里看到结果,我建议您使用以下代码:

   required here
       \/
.then(async response => {
    console.log(response);
    console.log(await response.clone().json()); // read json result from cloned response
    return response.json();
})

或者直接登录第二个then:

.then(async response => {
   console.log(response);
   return response.json();
 })
.then(body => { 
   console.log(body); // it doesn't require any workarounds
   observer.next(body);
   observer.complete();
})

【讨论】:

    猜你喜欢
    • 2014-10-15
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2023-03-26
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    相关资源
    最近更新 更多