【问题标题】:Await not awaiting等待不等待
【发布时间】:2018-12-09 13:46:54
【问题描述】:

我开始使用 MathJax 和使用 await 我正在格式化一系列可以包含数学的行。数学由分隔符$...$ 表示。

问题:我需要等待 MathJax 完成它的转换(我确实得到了某种 html 输出)但是转换没有等待,format() 的其余部分正在执行。我的部分代码是根据question 中给出的答案建模的。

  function MJ(math) {
    // as per the documentation, this returns a promise if no callback is set
    return mathjax.typeset({
      math: math,
      format: "inline-TeX",
      html: true,
    });

  }

  async function convert(line) {
    var re = /\$(.*?)\$/;
    var match = re.exec(line)[0];
    var math = match.slice(1, -1);

    // ORIGINAL CODE
    // let result = await MJ(math).then(function(data){return line.replace(match,data.html);});
    // return result;

    let result = await MJ(math);
    console.log(`MJ is ready: ${result.html}`);
    return line.replace(match, result.html);
  }

  function format(line) {
    if(line.indexOf("$")>-1){
      line = convert(line).then( function(result) {
        console.log(result);
        return result;
      });

      console.log(line);
    }

    // additional formatting going below that needs to wait for the mathjax conversion
  }

错误输出(部分截断)

(node:17104) DeprecationWarning: Mongoose: mpromise (mongoose's default promise
library) is deprecated, plug in your own promise library instead: http://mongoos
ejs.com/docs/promises.html
Promise { <pending> }
TypeError: line.indexOf is not a function
    at emphasis (C:\something\routes\index.js:91:18)
    at format (C:\something\routes\index.js:139:12)
    at C:\something\routes\index.js:803:25
    at newTickHandler (C:\something\node_modules\m
promise\lib\promise.js:234:18)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)
MJ is ready: <span class="mjx-chtml"><span class="mjx-math" etc.
<span class="mjx-chtml"><span class="mjx-math" etc.

调用 format(lines[x]) 的位置

警告:不是最漂亮的代码。无需过多详细说明,我有“模块”,其中包含“片段”,其中包含我需要组合在一起以形成一个连贯文本的文本。

lines[x] 由如下所示的字符串组成:“Einstein 证明 $E = mc^2$。”

app.get('/flashcards/module/:id', isAuthenticated, function(req, res){
    var moduleid = new ObjectId(req.params.id);
    var user = new ObjectId(req.session.user);
    var categoryid = new ObjectId(req.query.categoryid);
    var back = "";
    var html, lines;
    var index = 0;
    var indexoflastline = 0;
    var active = false;
    var moduletitle = "";

    Modules.findOne( { _id: moduleid } )

    .then(function(module) {
      moduletitle = module.title;
      return Snippets.find( { _id: module.snippets } ).sort({order: 1})
    })

    .then(function(snippets){

      if(snippets){

        for (var i = 0; i < snippets.length; i++) {
          if(snippets[i].suppresstext == true) {
            snippets.splice(i,1);
            i-=1;
          }
        }

        html = "<ul>";

        for(var i = 0; i < snippets.length; i++) {

          if(i==0) {
            lines = snippets[i].main.split('\n').clean('');

            for(var x = 0; x < lines.length; x++){
              if(checkindex(lines[x])==indexoflastline) {
                html += "<li>";
                html += format(lines[x]);
                html += "</li>";
              } else if (checkindex(lines[x])>indexoflastline) {
                html += "<ul>";
                html += "<li>";
                html += format(lines[x]);
                html += "</li>";
                indexoflastline += 1;
              } else if (checkindex(lines[x])<indexoflastline){
                html += "</ul>".repeat(indexoflastline-checkindex(lines[x]));
                html += "<li>";
                html += format(lines[x]);
                html += "</li>";
                indexoflastline -= indexoflastline-checkindex(lines[x]);
              }
            }

            indexoflastline = -1;
          }

          if(i>0){
            if(snippets[i].main!=snippets[i-1].main){

              html += "</ul>".repeat(indexoflastline+1);
              lines = snippets[i].main.split('\n').clean('');

              if(lines) {
                for(var x = 0; x < lines.length; x++){
                  if(checkindex(lines[x])==indexoflastline+1) {
                    html += "<li>";
                    html += format(lines[x]);
                    html += "</li>";
                  } else if (checkindex(lines[x])>indexoflastline+1) {
                    html += "<ul>";
                    html += "<li>";
                    html += format(lines[x]);
                    html += "</li>";
                    indexoflastline += 1;
                  } else if (checkindex(lines[x])<indexoflastline+1){

                    html += "</ul>".repeat(indexoflastline+1-checkindex(lines[x]));
                    html += "<li>";
                    html += format(lines[x]);
                    html += "</li>";
                    indexoflastline = indexoflastline-checkindex(lines[x]);
                  }
                }

              // indexoflastline = -1;
              }
            } else if (snippets[i].main==snippets[i-1].main){
              // index of snippet from previous snippet
              lines = snippets[i-1].subinformation.split('\n').clean('');
              indexoflastline = checkindex(lines[lines.length-1]);

              if(indexoflastline===undefined)
                indexoflastline = -1;

              indexoflastline = checkindex(lines[lines.length-1])+1 ? checkindex(lines[lines.length-1]) : -1;
            }
          }

          lines = snippets[i].subinformation.split('\n').clean('');

          if(lines){

            for(var x = 0; x < lines.length; x++){
              if(indexoflastline==-1) {
                html += "<ul>";
                html += "<li>";
                html += format(lines[x]);
                html += "</li>";
                indexoflastline = 0;
              } else if(checkindex(lines[x])==indexoflastline) {

                html += "<li>";
                html += format(lines[x]);
                html += "</li>";
              } else if (checkindex(lines[x])>indexoflastline) {

                html += "<ul>";
                html += "<li>";
                html += format(lines[x]);
                html += "</li>";
                indexoflastline += 1;
              } else if (checkindex(lines[x])<indexoflastline){
                html += "</ul>".repeat(indexoflastline-checkindex(lines[x]));
                html += "<li>";
                html += format(lines[x]);
                html += "</li>";
                indexoflastline -= indexoflastline-checkindex(lines[x]);
              }

              if(x==lines.length-1 && i < snippets.length-1) {
                if (snippets[i].main == snippets[i+1].main){
                  indexoflastline = checkindex(lines[x]);
                } else if (x==lines.length-1) {
                  html += "</ul>".repeat(indexoflastline+1);
                  indexoflastline = -1;
                }
              }
            }
          } else if (snippets[i].main == snippets[i+1].main) {
            if(x==lines.length-1 && i < snippets.length-1) {
              indexoflastline = checkindex(lines[x]);
              if (x==lines.length-1) {
                html += "</ul>".repeat(indexoflastline+1);
                indexoflastline = -1;
              }
            }
          }
        }

      if(i == snippets.length-1){
        for(var z = indexoflastline; z > 0; z--)
          html +="</ul>";
      }

      html += "</ul>"

      html += "</br>".repeat(2);

    return Categories.findOne( { _id: categoryid } );
  })

  .then(function(category) {
    back = `/flashcards/${category.parent}`;
    return userCategories.findOne( { category: categoryid, user: user } );
  })

  .then(function(userCategory) {
    res.render('user/flashcards/module', {
      moduleid: moduleid,
      moduletitle: moduletitle,
      back: back,
      htmlstring: html,
      selected: userCategory.active,
      admin: req.session.admin,
      categoryid: categoryid
    });

    return true;
  })

  .catch(function(err){
    if(err)
      return console.log(err);
  });
});

【问题讨论】:

  • 不确定,但我认为或者你使用“then”或者你使用 await
  • 你能详细说明一下吗?
  • 看起来不是 String 的东西被传递给format()
  • 如果您指的是 TypeError,我认为这是因为我在 format() 函数中设置了 line = convert(line),我希望在其中得到一个字符串,但是我得到了一个未决的承诺......代码有效否则在我不必使用 mathjax 的情况下。
  • format 的准确调用方式/位置?

标签: javascript node.js promise async-await mathjax


【解决方案1】:

你把 promise 和 await 混在一起了。不要那样做。你无法理解自己的代码。这是你的错误:

line = convert(line).then( function(result) {
        console.log(result);
        return result;
      });
console.log(line); // This is called before convert() finishes, of course it's a pending promise. 

要么使用=await,要么使用promise 并使用then 解析中的返回值。

line = await convert(line);
console.log(line); 

【讨论】:

  • 要做到line = await convert(line);,OP还必须使包含函数async
【解决方案2】:

不要将await 和 Promise 混在一起,试试这样。调试行打印正确吗?

let data = await MJ(math);
console.log("MJ is ready: ${data}");
return line.replace(match, data.html);

【讨论】:

  • 输出没有显着变化:Promise { &lt;pending&gt; } 如果我在调用convert() 后插入console,log(line)。我已经在上面包含了我的控制台输出。
猜你喜欢
  • 1970-01-01
  • 2018-05-04
  • 2020-05-09
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 2016-07-07
  • 2016-03-25
相关资源
最近更新 更多