簡體   English   中英

promise 鏈的問題

[英]Issue with promise chain

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#bodyReadableStream 一個 stream 只能消耗一次然后就空了。 由於Body#json()方法將 stream 讀取到完成,因此您第二次嘗試使用相同的主體時,您正在利用一個空的 stream。 這就是為什么Response API 實現鎖定 stream 並且不允許調用該方法兩次。

你可以自己試試:

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

調用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();
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM