Return observable from async function

Fri*_*tra 3 javascript promise observable async-await firebase

TLDR; I have a Promise collection().add() which resolves to an object DocumentReference with a listener function onSnapshot() that emits data.

I need to return an Observable which, upon subscription, calls the Promise, subscribes to the listener function on the resolved object, and broadcasts the values from the listener to subscriber.next()

Context: I am trying to declare a function that creates a Firestore document, then returns an Observable with the document data, using the onSnapshot() function on its DocumentReference returned by collection().add().

Based on: https://github.com/EddyVerbruggen/nativescript-plugin-firebase/blob/f6972433dea48bf1d342a6e4ef7f955dff341837/demo-ng/app/item/items.component.ts#L175-L185

async create(project) {
    const ref = await this.db.collection('projects').add(project);
    return new Observable(subscriber => {
        ref.onSnapshot(doc => {
            // ...
            subscriber.next(doc.data());
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

Current behaviour:async/await always returns a Promise, I need the function to return an observable.

Expected: I need a slice of data from the ref.onSnapshot() callback, in this case doc.data(), to use it in my template, e.g.

// ... 

this.service.create(project).subscribe(project => console.log(project));
Run Code Online (Sandbox Code Playgroud)

B M*_*B M 8

在您的实现中create返回一个承诺,因为正如您所指出的,它需要工作async。如果这是事实,那么您必须修改上下文调用create:也只需创建调用函数asyncawait在调用之前添加create: await create(...)

作为替代方案,如果您无论如何都想返回一个 observable,您必须停止awaitingdb.collection().add()并删除asyncbefore create。然后你可以直接返回 observable 并且在你的.then函数内部db.collection().add()可以更新 observable doc.data()

create(project) {
    return new Observable(subscriber => {
        this.db.collection('projects').add(project)
           .then(ref => {
                ref.onSnapshot(doc => {
                    // ...
                    subscriber.next(doc.data());
                });
           });
    });
}
Run Code Online (Sandbox Code Playgroud)

请注意,这await只是处理Promise. 更经典的方法是将回调附加到其.then. 请注意,.then再次返回 a Promise,它再次具有 a.then等等 - 这就是Promises 的定义方式。