如何 return 从回调中解决的承诺

How to return a promise resolved from a callback

我的 promise 逻辑有问题(对 JS 来说还是很新),我找不到问题所在。 看看我做自己想做的事有多难,我只能猜测这不是正确的做法。我确实找到了另一种修复它的方法,但我仍然对是否有办法做我想做的事感兴趣。

以下是一些详细信息:

我有一个 MessageQueue.sendMessage(),它添加了我给 PendingMessageCache 的消息。如果可以,MessageQueue 获取缓存并将 Message 发送到服务器。

有时我需要在消息发送后做一些事情。所以我添加了一个callback,在发送消息时由MessageQueue保存和调用。它工作得很好。调用基本上是这样的:

await MessageQueue.sendMessage(myMsg, () => {markMessageAsSent()});

对于一种新型的消息,我需要等待消息被有效发送,因为应用程序在它之后被完全清理。

由于 sendMessage 只是将消息添加到 cache 和 returns,callback 稍后会被调用,但 在这种情况下也是如此迟到,应用已重启。

该消息基本上是 lastMessage 发送到服务器,表示此用户删除了特定应用程序实例。

所以我认为我想要的是这样的:

deleteAccount = async () => {
    const aMagicalCallback;

    // this call adds the message to the cache, 
    // and ask the MessageQueue to call aMagicalCallback when that lastMsg is sent
    await MessageQueue.sendLastMessage(lastMsg, <aMagicalCallback>);
    // return the callback which would be a promise.
    // this promise is resolved when it is resolved 
    // when the MessageQueue invokes the callback <aMagicalCallback>
    return <aMagicalCallback>;
}

基本上我想做的是

    // wait for the lastMessageBeingEffectively sent
    await deleteAccount();
    app.eraseEverything();
    app.restart();

如果一点都不清楚,请告诉我。 感谢

据我了解,您已经为每条消息添加了回调函数。您可以让原始回调检查消息队列的大小并执行

,而不是考虑在创建 promise 后注入单独的回调
app.eraseEverything();
app.restart();

空的时候。

您应该 return 一个 Promise 而不是使用 async。所以你可以选择何时 resolve promise,即使是在嵌套的回调函数中:

deleteAccount = () => new Promise(resolve => {
    MessageQueue.sendLastMessage(lastMsg, () => {
        // do your thing
        resolve();
    });
});

然后你可以像一个普通的async函数一样等待它

// this awaits until the resolve() above has been called
await deleteAccount();

app.eraseEverything();
app.restart();