[英]RxJS Observable - Wait for async method to complete before using next emitted value
[英]RxJS Node wait for observable to complete before subscribing to the next in sequence
我正在嘗試使用從Google工作表中抓取的值填充數據庫。 hasuraHelper.insert()在我的數據庫中進行HTTP發布。 我如何做到只有在上一個api調用返回后才能調用insert()? 我以為concatMap可以解決問題,但似乎它仍然急切地同意所有排放。
當前:請求1->請求2-> ...->請求1完成->請求2完成-> ...
我想要的是:請求1->請求1完成->請求2->請求2完成-> ...
以下是相關代碼:
sheetsHelper.authToken()
.flatMap(sheetsHelper.get)
.flatMap(response => response.values) //values is a 2d array
.map(row => {
console.log(row[0]);
const flights = [];
//add 100-500 objects to this array
return flights;
})
.flatMap(flights => {
const arrayOfFlightArrays = [];
//max batch size of 50
while (flights.length) {
const flightArr = flights.splice(0, 50);
arrayOfFlightArrays.push(flightArr);
}
return Rx.Observable.from(arrayOfFlightArrays);
})
.concatMap(flights => hasuraHelper.insert(flights) //insert flights into table
.retry())
.map(response => response.data)
.subscribe(console.log, console.error);
這是插入的樣子:
exports.insert = function (objects) {
return Rx.Observable.fromPromise(axios({
method: 'post',
url: '/',
data: {
type: "insert",
args: {
table: "flights",
objects: objects
}
}
}));
};
您的插入函數不是惰性的。 您正在將執行中的諾言包裝在Observable中,但它已經在執行中。
為了保證在訂閱時變得懶惰並開始處理,您需要將其包裝在Rx.Observable.defer(() => Rx.Observable.fromPromise(axios(/* ... */))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.