2017-04-16 38 views
0

我正在嘗試創建一個Chrome擴展,它將發出一系列POST請求,每個請求的參數都依賴於前一個請求的響應。我正在使用fetch執行此操作。我理解如何使用。然後處理單個查詢的組件之間的依賴關係,但是如何處理跨查詢的依賴關係?所以,目前我的分機有一個像如何在Chrome擴展中鏈接一系列POST請求?

fetch('http://localhost:8081/seed/create', { 
     method: 'post', 
     headers: new Headers({ 
      'Accept': 'application/json, text/plain, */*', 
      "Content-Type": "application/json; charset=UTF-8" 
     }), 
     body: '{"name": "nutch","seedUrls":[{"seedList": null,"url": "http://nutch1.apache.org/"}]}' 
    }) 
      .then(function (response) { 
         return response.text(); 
      }) 
      .then(function (text) { 
       seed = text; 
       console.log(seed); 
       document.getElementById("post").innerHTML = "responsePost: " + seed; 

      }) 
      .catch(function (error) { 
       console.log('FAIL: ', error); 
      }); 

}); 

代碼,但後來我還需要第二次POST請求必須等待第一次成功,並與之前的響應來填充它的有效載荷。有小費嗎?? 謝謝!

+1

另一個。然後結束。或者使用[async await](https://developers.google.com/web/fundamentals/getting-started/primers/async-functions) –

+0

啊謝謝你,我會試試:) –

回答

0

好我要回答我的問題 - 我把丹尼爾的意見,並使用異步操作,這是一個更容易的許諾來閱讀:

async function getNutch(url) { 

var response; 
try { 
    response = await fetch(url + "seed/create", { 
     method: 'post', 
     headers: new Headers({ 
      'Accept': 'application/json, text/plain, */*', 
      "Content-Type": "application/json; charset=UTF-8" 
     }), 
     body: getPayload(payloadEnums.SEED) 
    }); 
    seedDir = await response.text(); 
    console.log(seedDir); 
} catch (err) { 
    console.log('fetch failed: ', err); 
} 
try { 
    response = await fetch(url + "job/create", { 
     method: 'post', 
     headers: new Headers({ 
      'Accept': 'application/json, text/plain, */*', 
      "Content-Type": "application/json; charset=UTF-8" 
     }), 
     body: getPayload(payloadEnums.JOB) 
    }); 
    console.log(await response.text()); 
} catch (err) { 
    console.log('fetch failed: ', err); 
} 

}

(至少對我來說!)

這迫使兩個查詢順序運行,第二個必須等到第一個完成 - 這是我想要的。如果沒有這種依賴關係,您應該並行運行查詢,如Daniel提供的鏈接中所解釋的那樣。