gpt4 book ai didi

javascript - 如何有条件地等待 promise 解决?

转载 作者:行者123 更新时间:2023-11-30 09:41:10 25 4
gpt4 key购买 nike

我调用一个函数,

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 的赋值包装在一个 promise 中,然后使 getResponse then() 能够,但这似乎有点过多,因为我只有一个案例,我有一堆异步工作正在完成以确定 someVar

最佳答案

Note, replaced callSomeOtherFunctionWhichDoesABunchOfDatabaseQueriesThatUsePromisesAndEventuallySetssomeVar with someFunc in code below :p

getResponse 总是需要返回一个 promise

所以

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));

if someFunc resolves to the value it sets someVar to, you could make the code a little nicer

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 以其他方式使用,那可能就没用了

关于javascript - 如何有条件地等待 promise 解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41153881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com