簡體   English   中英

如何有條件地等待諾言解決?

[英]How to conditionally wait for a promise to resolve?

我叫一個函數

getResponse(Math.random());
doSomethingWith(someVar);


getResponse(num) {
  if(num > 0.8) someVar = "whee";
  if(num > 0.5) someVar = "whoo";
  if(num > 0) callSomeOtherFunctionWhichDoesABunchOfDatabaseQueriesThatUsePromisesAndEventuallySetssomeVar();
}

有什么方法可以等待callSomeOtherFunctionWhichDoesABunchOfDatabaseQueriesThatUsePromisesAndEventuallySetssomeVar()完成並設置someVar嗎? 我以為我也可以將someVar的分配someVar在一個promise中,然后使getResponse then()可能,但這似乎有點多余,因為我只有一種情況,我需要做大量異步工作來確定someVar

注意,在下面的代碼中,用callSomeOtherFunctionWhichDoesABunchOfDatabaseQueriesThatUsePromisesAndEventuallySetssomeVar代替了someFunc

getResponse必須始終返回承諾

所以

function getResponse(num) {
    return Promise.resolve()
    .then(() => {
        if (num > 0.8) {
            someVar = "whee";
            return;
        }
        if (num > 0.5) {
            someVar = "whoo";
            return;
        }
        if (num > 0) {
            return someFunc();
        }
    });
}

請注意-您的原始代碼中的邏輯將(幾乎)始終運行該長函數,因為Math.random()幾乎始終> 0

剩下的代碼就是

getResponse(Math.random())
.then(() => doSomethingWith(someVar));

如果someFunc解析為其設置someVar的值,則可以使代碼更好

var getResponse = num => Promise.resolve()
.then(() => {
    if (num > 0.8) {
        return "whee";
    }
    if (num > 0.5) {
        return "whoo";
    }
    return someFunc();
});

getResponse(Math.random())
.then(someValue => doSomethingWith(someValue));

但這如果以其他方式使用someVar可能沒有用

暫無
暫無

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

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