Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 等待决不解决,之后的下一行决不执行_Javascript_Node.js_Ecmascript 6_Promise_Async Await - Fatal编程技术网

Javascript 等待决不解决,之后的下一行决不执行

Javascript 等待决不解决,之后的下一行决不执行,javascript,node.js,ecmascript-6,promise,async-await,Javascript,Node.js,Ecmascript 6,Promise,Async Await,我使用的是async await,我的await永远不会解析,所以下一行根本不会执行。我指的是这一行: result = await IndexingStatusResult(req, res); 在以下代码中: router.post( "/api/result-store/v1/indexing-analyzer/:searchID/:id", async (req, res) => { console.log("Indexing started"); var

我使用的是async await,我的await永远不会解析,所以下一行根本不会执行。我指的是这一行:

result = await IndexingStatusResult(req, res);
在以下代码中:

router.post(
  "/api/result-store/v1/indexing-analyzer/:searchID/:id",
  async (req, res) => {
    console.log("Indexing started");
    var hrstart = process.hrtime();
    let result = null;

    result = await IndexingStatusResult(req, res);
    console.log("result is: ", result.data);
    hrend = process.hrtime(hrstart);
    console.info("Execution time (hr): %ds %dms", hrend[0], hrend[1] / 1000000);

    res.status(200).send({
      indexingTimeSec: hrend[0],
      indexingTimeMillSec: hrend[1] / 1000000
    });
  }
);
但正如你在IndexingStatusResult中看到的,当一切都完成时,我会回报你一个承诺:

const IndexingStatusResult = async (req, res) => {
  const docID = parseInt(req.params.id) * 1000;
  const dbName = "test_" + req.params.searchID;
  let result = null;
  try {
    result = await axios(
      `${params.HOST_NAME_WITH_PROTOCOL}/${dbName}/_design/searchAll/_search_info/searchAll`
    );
    result = result.data;
    console.log(
      "Number of docs indexed:",
      result.search_index.doc_count,
      "Total Docs needs to be indexed:",
      docID
    );
  } catch (e) {
    console.log(e);
  }
  console.log(`result returned is : ${JSON.stringify(result)}`);
  if (!result || parseInt(result.search_index.doc_count) < docID) {
return Promise.resolve(
  setTimeout(() => {
    console.log("WWWWWAAAAIIIIIITING");
    IndexingStatusResult(req, res);
  }, 5000)
);
  } else {
    console.log("YAAAAAAYYYYYYYYYYYYY");
    return Promise.resolve(result);
  }
};
因此,以下行永远不会执行:

console.log("result is: ", result.data);
我做错什么了吗?

有几个问题:

  • 你写“但是正如你在
    索引状态结果中看到的那样,
    当一切都完成时,我会返回一个承诺”。此语句显示了一个错误的概念:
    async
    函数同步返回承诺,而不是在“一切”(异步)完成时返回承诺
  • “我的等待永远无法解决”:是的,而且比你想象的要快。语句
    console.log(“result is:”,result.date)
    确实会执行,但它是触发错误的语句
  • IndexingStatusResult
    中调用
    setTimeout
    不会延迟它返回的承诺的解决时刻。由于在调用
    setTimeout
    后不再执行任何操作(在编辑中,您将在此处显式返回),因此该承诺将在
    未定义的情况下实现。
    在此阶段,
    setTimeout
    回调尚未执行。
    未定义的
    分辨率值解释了您得到的错误
  • 还应该注意的是,您已经有了
    result=result.data
    ,因此即使您将其作为解析值返回,
    result.data
    也不存在
  • 不要调用
    setTimeout
    ,而是执行
    wait delay(5000)
    ,其中
    delay
    返回超时后解析的承诺
  • async
    函数中,不需要将返回值包装为承诺。如上所述,promise对象已经返回,实际的
    return
    语句应该指示该promise现在应该解析的值
因此(无需测试),我想说这段代码会做得更好:

router.post(
  "/api/result-store/v1/indexing-analyzer/:searchID/:id",
  async (req, res) => {
    console.log("Indexing started");
    var hrstart = process.hrtime();
    let result = null;

    result = await IndexingStatusResult(req, res);
    console.log("result is: ", result); // not .data
    hrend = process.hrtime(hrstart);
    console.info("Execution time (hr): %ds %dms", hrend[0], hrend[1] / 1000000);

    res.status(200).send({
      indexingTimeSec: hrend[0],
      indexingTimeMillSec: hrend[1] / 1000000
    });
  }
);

// Helper function that's very useful in async functions:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

const IndexingStatusResult = async (req, res) => {
  const docID = parseInt(req.params.id) * 1000;
  const dbName = "test_" + req.params.searchID;
  let result = null;
  while (true) {
    try {
      result = await axios(
        `${params.HOST_NAME_WITH_PROTOCOL}/${dbName}/_design/searchAll/_search_info/searchAll`
      );
      result = result.data;
      console.log(
         "Number of docs indexed:",
        result.search_index.doc_count,
        "Total Docs needs to be indexed:",
        docID
      );
    } catch (e) {
      console.log(e);
      return e; // ?? determine what you want to happen...
    } 
    console.log(`result returned is : ${JSON.stringify(result)}`);
    if (result && parseInt(result.search_index.doc_count) >= docID) break;
    await delay(5000); // delay and keep looping
  }
  console.log("YAAAAAAYYYYYYYYYYYYY");
  return result;
};

这是完整的日志吗?我认为
的结果是:“
应该至少发射一次(结果
未定义
)。在这种情况下,还应该有一个未处理的promise异常错误(访问
结果。数据
应该抛出)。@Joseph谢谢Joseph是的,你是对的,我知道了,然后是上面的日志。我没有把完整的日志。更新的日志请查看:)应该注意,如果您的
条件满足,则不会返回任何内容——您可能应该将该
设置超时
包装在承诺中并返回它(使用递归调用
索引状态结果
的结果解决该问题).@HereticMonkey感谢您的输入,但在此之前,我很好奇为什么会看到此错误:TypeError:无法读取未定义的属性“data”,因为在完成IndexingStatusResult之前,Wait不应解析,如果它进入您的
,如果它永远无法解析,并将返回未定义的
而不是承诺。
router.post(
  "/api/result-store/v1/indexing-analyzer/:searchID/:id",
  async (req, res) => {
    console.log("Indexing started");
    var hrstart = process.hrtime();
    let result = null;

    result = await IndexingStatusResult(req, res);
    console.log("result is: ", result); // not .data
    hrend = process.hrtime(hrstart);
    console.info("Execution time (hr): %ds %dms", hrend[0], hrend[1] / 1000000);

    res.status(200).send({
      indexingTimeSec: hrend[0],
      indexingTimeMillSec: hrend[1] / 1000000
    });
  }
);

// Helper function that's very useful in async functions:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

const IndexingStatusResult = async (req, res) => {
  const docID = parseInt(req.params.id) * 1000;
  const dbName = "test_" + req.params.searchID;
  let result = null;
  while (true) {
    try {
      result = await axios(
        `${params.HOST_NAME_WITH_PROTOCOL}/${dbName}/_design/searchAll/_search_info/searchAll`
      );
      result = result.data;
      console.log(
         "Number of docs indexed:",
        result.search_index.doc_count,
        "Total Docs needs to be indexed:",
        docID
      );
    } catch (e) {
      console.log(e);
      return e; // ?? determine what you want to happen...
    } 
    console.log(`result returned is : ${JSON.stringify(result)}`);
    if (result && parseInt(result.search_index.doc_count) >= docID) break;
    await delay(5000); // delay and keep looping
  }
  console.log("YAAAAAAYYYYYYYYYYYYY");
  return result;
};