簡體   English   中英

如何返回從回調中解析的 promise

[英]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並返回,因此稍后會調用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而不是使用async 因此,您可以選擇何時解析 promise,即使在嵌套回調 function 中:

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

然后你可以像普通的async function 一樣等待它

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

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

據我了解,您已經在每條消息中添加了回調 function 。 與其考慮在創建 promise 之后注入單獨的回調,不如讓原始回調檢查消息隊列的大小並執行

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

當它是空的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM