如何有条件地等待承诺解决?

时间:2016-12-14 23:16:41

标签: javascript promise ecmascript-6

我叫一个函数,

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的作业包含在一个承诺中,然后让getResponse then()能够,但这似乎有点过分,因为我只有一个案例,我有一个正在进行一系列异步工作以确定someVar

1 个答案:

答案 0 :(得分:4)

  

注意,在下面的代码中将callSomeOtherFunctionWhichDoesABunchOfDatabaseQueriesThatUsePromisesAndEventuallySetssomeVar替换为someFunc:p

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以其他方式使用

,那可能没用