尽管已调用promise resolve(),但异步函数不会返回

时间:2019-08-18 00:55:37

标签: javascript node.js typescript

尝试在使用“新Promise <...”方法的异步函数中使用“行读取器”遍历文件中的行。在调试器中,我可以确认调用了resolve函数,但是async函数从不返回。有点困惑。

异步功能:

import * as lineReader from 'line-reader';
import * as fs from 'fs';

export async function iterateMyFileAsync(filename: string): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      if (!fs.existsSync(filename)) {
        reject(new Error("file " + filename + " doesn't exist"));
        return;
      }

      lineReader.eachLine(filename, (line, last) => {

        // would want to do things, but issue repros without anything here

        if (last) {
          resolve()
        }
      });
    });
}

其他地方:

await iterateMyFileAsync('myfile.txt');

在调试器中,我可以确认肯定调用了resolve(),但iterateMyFileAsync()永不返回。为什么会发生这种情况?

3 个答案:

答案 0 :(得分:0)

经过一些挖掘和同行评论后的更新

您已将功能标记为async,它将自动将您的功能转换为Promise。不必再次履行承诺。

line-reader软件包由于某些我无法解释的原因而无法正常工作。从npm起,它的最新发布时间是3年前。 check this codesanbox for failing exemplesline-reader eachLineonpen API。

尝试使用n-readlines npm软件包。我设法使其正常工作,并且适合您的用例。或者,您可以尝试节点built in package readLine

import lineByLine from 'n-readlines';
import * as fs from 'fs';

export async function iterateMyFileAsync(filename: string): Promise<void> {
  if (!fs.existsSync(filename)) {
    throw new Error('file ' + filename + " doesn't exist");
  }

  const liner = new lineByLine(filename);
  let line;

  while ((line = liner.next())) {
    console.log('Line ', line.toString('ascii'));
  }

  return;
}

答案 1 :(得分:0)

如果您的文件为empty,则您的承诺将为not resolve

这是输入文件为空时line-reader的规格:

        it("should not call callback on empty file", function(done) {
          lineReader.eachLine(emptyFilePath, function(line) {
            assert.ok(false, "Empty file should not cause any callbacks");
          }, function(err) {
            assert.ok(!err);
            done()
          });
        });

您应该像这样修改代码以处理empty file情况:

    import * as lineReader from 'line-reader';
    import * as fs from 'fs';

    export async function iterateMyFileAsync(filename: string): Promise<void> {
      return new Promise<void>((resolve, reject) => {
        if (!fs.existsSync(filename)) {
          reject(new Error("file " + filename + " doesn't exist"));
          return;
        }

        lineReader.eachLine(filename, (line, last) => {
          // would want to do things, but issue repros without anything here
        },
          (err) => {
            if (err) {
              reject(err)
              return;
            }

            resolve()
          });
      });
    }

答案 2 :(得分:0)

更新:问题发布后不久,我解决了这个问题,很抱歉没有关闭此问题。这与调试工作流无法正常运行有关,应该在适当的时候没有遇到断点,这使我认为正在发生不可能的事情。