从涉及承诺的函数返回非承诺值 [英] return a non promise value from a function involving promises
问题描述
我有一个名为"test_sheet"的函数,该函数应该返回一个值.然后将该值传递给测试器函数,该函数将告诉我是否通过了测试.
在我的"test_sheet"内部,我有一些由promise处理的异步操作.现在,如何从我的test_sheet函数返回一个(非承诺)值.
I have a function called "test_sheet" that is supposed to return a value. that value will then be passed to a tester function which will tell me if I passed or failed the test.
inside my "test_sheet" I have a few async operations which are handled by promises.
now, how can I return a (non-promise) value from my test_sheet function.
function test_sheet()
{
//all my logic will go here
new Promise(function(resolve, reject)
{
//simulating an async operation
setTimeout(() => resolve(true), 1000);
})
.then(function(res){return res});
}
function tester()
{
//not allowed to change this function in any way
if(test_sheet() == true)
console.log("pass!");
else
console.log("fail!");
}
tester();
还有更好的方法吗?
推荐答案
嗯,从技术上讲, tester()
可能保持原样:
Well, technically it is possible, tester()
may reamain intact:
var test_sheet=false;
function start_test()
{
//all my logic will go here
new Promise(function(resolve, reject)
{
//simulating an async operation
setTimeout(() => resolve(true), 1000);
})
.then(res => {
test_sheet=true;
tester();
});
}
function tester()
{
//not allowed to change this function in any way
test_sheet == true ? console.log("pass!") : console.log("fail!");
}
//tester();
start_test();
但是测试现在从 start_test()
开始,并且 test_sheet
成为变量,其唯一目的是充当参数-不能添加到 testing()
而无需对其进行修改.
这样,将无效的不良设计转换为不良的设计.
But the test starts with start_test()
now, and test_sheet
became a variable, with the sole purpose of acting as an argument - which could not be added to testing()
without modifying it.
A nonworking bad design is transformed to working bad desing this way.
这篇关于从涉及承诺的函数返回非承诺值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!