【问题标题】:How can we wait for a result in JavaScript?我们如何在 JavaScript 中等待结果?
【发布时间】:2018-09-05 16:05:06
【问题描述】:

我一直在到处寻找有关 Promise 或 async/await 的信息,但它们似乎不起作用。我需要从查询函数中获取当前日期,然后才能在后续函数中使用该日期。这是迄今为止我最好的猜测:

    // Retrieve current session date
    var currentDate;
    async function getMaxDate() {

        fetch(url).then((data) => {
            return data.json();
        }).then((json) => {

            // This is the date used in queries
            currentDate = json[obj].max.substr(0, 10);
            console.log(currentDate);

            return new Promise(resolve => {
                setTimeout(() => {
                    resolve(currentDate);
                }, 5000);
            });

        }).catch((e) => {
            console.error('There was an error:');
            console.log(e);
        });

    }


  async function getAllData() {
        try {
            currentDate = await getMaxDate();
            await getMarket(currentDate);
            console.log(currentDate);
        } catch (error) {
            console.log('An error occurred.');
        }
    }

    // This function is called when the document is first loaded
    $(function () {
        let promise = getAllData();
    });

但是无论有没有 promise/async/await,行为都是相同的 - currentDate 直到几秒钟后仍未定义。我也试过这样调用:

    getAllData()
        .then(function (currentDate) {
            console.log(currentDate);
        });

这里的 currentDate 直到稍后才定义。如需进一步说明 - getMaxDate 会进行一次提取,它可能会慢到足以导致此问题。因为稍后在该函数中,console.log(currentDate) 确实输出了正确的值。 (currentDate 被定义为一个全局变量。)但这就像我的代码正在以随机顺序执行......

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您的函数不返回任何内容。如果你希望它返回currentDate,你必须明确地这样做。

    async function getAllData() {
        try {
            let currentDate = await getMaxDate();
            await getMarket(currentDate);
            console.log(currentDate);
    
            return currentDate;
        } catch (error) {
            console.log('An error occurred.');
        }
    }
    

    返回值将是在 thenawait 情况下分配的值:

    let currentDate = await getAllData();
    
    getAllData.then(currentDate => {
      // ...
    });
    

    【讨论】:

    • 除此之外,文档说“一个 Promise,它将使用异步函数返回的值来解决,或者被异步函数中抛出的未捕获异常拒绝。” -Developer Mozilla。因此,如果您需要捕获/拒绝链,请拒绝捕获未捕获的异常。
    • 感谢您的建议。我添加了返回值,并尝试了您的 .then 但 currentDate 仍然未定义......也许我需要使用回调函数?
    • 您确定您要求的currentDate 与您分配的相同吗?在您的代码中,它是一个局部变量(通过let),因此它不会在外部可见。
    • currentDate 较早地被分配为全局变量。但我尝试使用 currentDate2(本地)并得到相同的未定义结果。
    • 再次感谢,结果证明是没有正确返回值,也没有将所有内容包装在 Promise 中。
    【解决方案2】:

    看看下面: 工作示例jsFiddle

    let currentDate;
    const url = 'https://jsonplaceholder.typicode.com/posts/1';
    
    function getMaxDate() {
      return new Promise(resolve => {
        fetch(url).then(data => {
          return data.json();
        }).then(json => {
          console.log('data from api', json);
          currentDate = new Date(); // here I simulate to get Date
          console.log(currentDate);
          resolve(currentDate);
        }).catch(error => {
          console.error('There was an error:');
          console.log(e);
          reject(error);
        });
      })
    
    }
    
    
    function getMarket(date) {
      return new Promise(resolve => {
        resolve({
          market: 'US',
          date
        });
      });
    }
    
    async function getAllData() {
      try {
        let currentDate = await getMaxDate();
        console.log('getAllData', currentDate);
        return await getMarket(currentDate);
      } catch (error) {
        console.log('An error occurred.');
      }
    }
    
    // This function is called when the document is first loaded
    $(function () {
      getAllData().
      then(result => {
        console.log('do sth...', result);
      });
    });
    

    【讨论】:

    • "你正在等待的函数必须返回一个 Promise"。异步函数也可以返回非承诺值。它们将自动包装在已解决的承诺中。
    • 非常感谢您的帮助。该代码仍然给我相同的未定义结果。一定是我的 getMaxDate 函数返回数据的时间太长了。也许我会尝试不同的方法。
    • 我需要更长的超时时间吗?或者可能是回调方法?
    • 最好是查看您的 getMaxDate 函数。没有任何建议都很难。
    • 好的,我添加了我的 getMaxDate 函数。
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多