无法从“异步”函数获取返回值-Javascript

时间:2018-11-23 06:15:01

标签: javascript

我正在使用javascript中的一些异步函数,但是我遇到了一个问题,我已经发布了here,但这对每个人来说都是不切实际的经验。现在,我做了一个内部成员函数相同的简单构造函数,并返回了一个值,但对我来说似乎是同样的问题,我尽了最大努力,但我不知道出了什么问题,如果您运行此代码,则可以检查我想要的是。这是JSfiddle上的demo link,您可以在console上看到结果。

这是我的代码

function Test() {
  this.init = async function() {
    var count = 0,
      page_job_details = null;

    async function waitMore() {
      console.log("Wait more loaded - " + (count + 1) + "...");
      let p = new Promise(function(res, rej) {
        setTimeout(async function() {
          if (count === 2) {
            res({
              page_job_details: "khan"
            });
          } else {
            count++;
            waitMore();
          }
        }, 2000);
      });
      var res = await p;
      if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
        console.log("waiting more...");
        waitMore();
      } else {
        console.log("Response is : " + res.page_job_details);
        return res;
      }
    }
    var khan;
    await waitMore().then(function(r) {
      console.log(r);
      khan = r;
    });
    return khan;
  }
}
new Test().init().then(function(res) {
  console.log(res);
})

  

当您注释掉setTimeout()中的条件并简单地res({page_job_details:"khan"});时,您将在new Test().init().then(function(res){ console.log(res); })中得到结果。否则,这就是主要问题。

2 个答案:

答案 0 :(得分:3)

问题之一是您没有从promise中返回递归调用的结果。

不仅仅是递归调用

waitMore();

您似乎希望递归调用的结果能够在管道中返回

res(waitMore());

function Test() {
  this.init = async function() {
    var count = 0,
      page_job_details = null;

    async function waitMore() {
      console.log("Wait more loaded - " + (count + 1) + "...");
      let p = new Promise(function(res, rej) {
        setTimeout(async function() {
          if (count === 2) {
            res({
              page_job_details: "khan"
            });
          } else {
            count++;
            res(waitMore());
          }
        }, 2000);
      });
      var res = await p;
      if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
        console.log("waiting more...");
        waitMore();
      } else {
        console.log("Response is : " + res.page_job_details);
        return res;
      }
    }
    var khan;
    await waitMore().then(function(r) {
      console.log(r);
      khan = r;
    });
    return khan;
  }
}
new Test().init().then(function(res) {
  console.log(res);
})

答案 1 :(得分:2)

有两个问题:

  • waitMore内的setTimeout中,仅当res时才调用count === 2。否则,创建的承诺将永远无法解决,awaitwaitMore()可能会永远无法解决-相反,该线程将永远保持暂停状态。您可以通过致电res 来解决此问题,无论count是否为2-如果count 2多得多,请调用res另一个调用来调用waitMore

    res(waitMore());
    
  • this.init函数的级别上,如果需要等待更多时间,则需要await waitMore()(并将响应放入要返回的新变量中),因此正确地链接Promise:

    if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
      console.log("waiting more...");
      const newRes = await waitMore();
      return newRes;
    } 
    

function Test() {
  this.init = async function() {
    var count = 0,
      page_job_details = null;

    async function waitMore() {
      console.log("Wait more loaded - " + (count + 1) + "...");
      const p = new Promise((res, rej) => {
        setTimeout(() => {
          if (count === 2) res({ page_job_details: "khan" });
          else {
            count++;
            res(waitMore());
          }
        }, 2000);
      });
      const res = await p;
      if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
        console.log("waiting more...");
        const newRes = await waitMore();
        return newRes;
      } else {
        console.log("Response is : " + res.page_job_details);
        return res;
      }
    }
    var khan;
    await waitMore().then(function(r) {
      console.log(r);
      khan = r;
    });
    console.log('about to return from init')
    return khan;
  }
}
new Test().init().then(function(res) {
  console.log('in init callback')
  console.log(res);
})