从涉及承诺的函数返回非承诺值

时间:2018-08-16 16:44:09

标签: javascript node.js function asynchronous promise

我有一个名为“ test_sheet”的函数,应该返回一个值。然后将该值传递给测试器函数,该函数将告诉我是否通过了测试。
在我的“ test_sheet”内部,我有一些由promise处理的异步操作。 现在,如何从test_sheet函数返回一个(非承诺)值。

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

还有更好的方法吗?

3 个答案:

答案 0 :(得分:1)

从技术上讲,tester()可能会保持完整:

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()中。
这样,将无效的不良设计转换为不良的设计。

答案 1 :(得分:0)

test_sheet()总是返回一个承诺,因此请尝试使用async await或.then将其解析,然后将其馈送到tester()函数。

以这种方式呼叫您:

test_sheet().then(function(test_sheet){
tester(test_sheet)})

为此,您需要将布尔返回值从test_sheet()传递到tester(test_sheet)

答案 2 :(得分:-1)

如果您处理异步代码,则必须使用promise或callback并使用async / await处理才能将其更改为同步代码

例如

function test_sheet()
{
   //all my logic will go here

   return new Promise(function(resolve, reject) {
      //simulating an async operation
      setTimeout(() => resolve(true), 2000);
   })
}

async function tester()
{
   //not allowed to change this function in any way
   await test_sheet() == true ? console.log("pass!") : console.log("fail!");
}

tester();