sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-11-30 09:41:10 25 4
mua khóa gpt4 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.

1 Câu trả lời

Note, replaced callSomeOtherFunctionWhichDoesABunchOfDatabaseQueriesThatUsePromisesAndEventuallySetssomeVar với someFunc in code below :p

getResponse 总是需要返回一个 promise

Vì thế

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

nếu như 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
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com