*Observables * 和*Promises * 都用於處理JavaScript 中的非同步操作,但它們有一些關鍵區別:
承諾
範例:
const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Promise resolved!'); }, 1000); }); promise.then((value) => { console.log(value); });
可觀察值
範例:
import { Observable } from 'rxjs'; const observable = new Observable((subscriber) => { subscriber.next('First value'); setTimeout(() => { subscriber.next('Second value'); subscriber.complete(); }, 1000); }); const subscription = observable.subscribe({ next(value) { console.log(value); }, complete() { console.log('Observable complete'); } }); // To cancel the subscription subscription.unsubscribe();
何時使用每個
以上是Observable 與 Promise的詳細內容。更多資訊請關注PHP中文網其他相關文章!