简体   繁体   English

TypeError [ERR_INVALID_ARG_TYPE]:“原始”参数的类型必须为 Function。接收到的类型未定义

[英]TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type Function. Received type undefined

In the following code, I get this error:在下面的代码中,我收到此错误:

TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type Function. Received type undefined TypeError [ERR_INVALID_ARG_TYPE]:“原始”参数的类型必须为 Function。接收到的类型未定义

const sqlite3 = require('sqlite3').verbose();
const util = require('util');

async function getDB() {
  return new Promise(function(resolve, reject) {
    let db = new sqlite3.Database('./project.db', (err) => {
      if (err) {
        console.error(err.message);
        reject(err)
      } else {
        console.log('Connected to the project database.');
        resolve(db)
      }
    });
    return db
  });
}


try {
  // run these statements once to set up the db
  let db = getDB();
  db.run(`CREATE TABLE services(id INTEGER PRIMARY KEY, service text, date text)`);
  db.run(`INSERT INTO services(id, service, date) VALUES (1, 'blah', '01-23-1987')`)
} catch(err) {
  console.log(err)
}


const db = getDB();
const dbGetAsync = util.promisify(db.get);

exports.get = async function(service) {

  let sql = `SELECT Id id,
    Service service,
    Date date
    FROM services
    WHERE service  = ?`;

  const row = await dbGetAsync(sql, [service], (err, row) => {
    if (err) {
      console.error(err.message);
      reject(err)
    }
    let this_row = {'row': row.id, 'service': row.service};
    this_row ? console.log(row.id, row.service, row.date) : console.log(`No service found with the name ${service}`);
    resolve(this_row)
  });

  return row;
}

let row = exports.get('blah')

It says the problem is in line 31: const dbGetAsync = util.promisify(db.get);它说问题在第 31 行: const dbGetAsync = util.promisify(db.get);

$ mocha src/tests/testStates.js
C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\node_modules\yargs\yargs.js:1163
      else throw err
           ^

    TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type Function. Received type undefined
        at Object.promisify (internal/util.js:256:11)
        at Object.<anonymous> (C:\Users\Cody\Projects\goggle-indexer\src\state.js:32:25)
        at Module._compile (internal/modules/cjs/loader.js:701:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
        at Module.load (internal/modules/cjs/loader.js:600:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
        at Function.Module._load (internal/modules/cjs/loader.js:531:3)
        at Module.require (internal/modules/cjs/loader.js:637:17)
        at require (internal/modules/cjs/helpers.js:22:18)
        at Object.<anonymous> (C:\Users\Cody\Projects\goggle-indexer\src\tests\testStates.js:7:15)
        at Module._compile (internal/modules/cjs/loader.js:701:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
        at Module.load (internal/modules/cjs/loader.js:600:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
        at Function.Module._load (internal/modules/cjs/loader.js:531:3)
        at Module.require (internal/modules/cjs/loader.js:637:17)
        at require (internal/modules/cjs/helpers.js:22:18)
        at C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\lib\mocha.js:330:36
        at Array.forEach (<anonymous>)
        at Mocha.loadFiles (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\lib\mocha.js:327:14)
        at Mocha.run (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\lib\mocha.js:804:10)
        at Object.exports.singleRun (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\lib\cli\run-helpers.js:207:16)
        at exports.runMocha (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\lib\cli\run-helpers.js:300:13)
        at Object.exports.handler.argv [as handler] (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\lib\cli\run.js:296:3)
        at Object.runCommand (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\node_modules\yargs\lib\command.js:242:26)
        at Object.parseArgs [as _parseArgs] (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\node_modules\yargs\yargs.js:1087:28)
        at Object.parse (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\node_modules\yargs\yargs.js:566:25)
        at Object.exports.main (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\lib\cli\cli.js:63:6)
        at Object.<anonymous> (C:\Users\Cody\AppData\Roaming\npm\node_modules\mocha\bin\_mocha:10:23)
        at Module._compile (internal/modules/cjs/loader.js:701:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
        at Module.load (internal/modules/cjs/loader.js:600:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
        at Function.Module._load (internal/modules/cjs/loader.js:531:3)
        at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
        at startup (internal/bootstrap/node.js:283:19)
        at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

I'm having problems using this promisify library.我在使用这个 promisify 库时遇到问题。

First of all no need to use return db;首先不需要使用return db; inside new Promise() because it is not expecting any return value from the callback function.new Promise() 中,因为它不期望回调函数有任何返回值。

Since getDB() is an asynchronous function, it needs to be used with await keyword to get the value or will be available in handler function of .then .由于 getDB() 是一个异步函数,它需要与await关键字一起使用才能获取值,否则将在.then处理函数中可用。

It doesn't make sense to me that you are calling getDB() multiple times.您多次调用getDB()对我来说没有意义。

It is better to read if instead of directly assigning an anonymous function to exports object key like this exports.get = async function() and then use it from exports object for use in same file, it would be better to define a named get function and then use it as well as export it.如果不是像这样直接将匿名函数分配给导出对象键,例如这样的exports.get = async function() ,然后从导出对象中使用它以在同一个文件中使用它,那么最好阅读,最好定义一个命名的get函数然后使用它以及导出它。

You are using reject and resolve keywords outside new promise() constructor which is not possible.您在new promise()构造函数之外使用了 reject 和 resolve 关键字,这是不可能的。

I have rewritten your code, I am not sure if I have missed anything, but do take a look and please inform if you are still facing any issues.我已经重写了你的代码,我不确定我是否遗漏了什么,但请看一看,如果你仍然面临任何问题,请告知。

const sqlite3 = require("sqlite3").verbose();
const util = require("util");

async function getDB() {
  return new Promise(function(resolve, reject) {
    let db = new sqlite3.Database("./project.db", err => {
      if (err) {
        console.error(err.message);
        reject(err);
      } else {
        console.log("Connected to the project database.");
        resolve(db);
      }
    });
  });
}

try {
  // run these statements once to set up the db
  let db = await getDB();
  db.run(
    `CREATE TABLE services(id INTEGER PRIMARY KEY, service text, date text)`
  );
  db.run(
    `INSERT INTO services(id, service, date) VALUES (1, 'blah', '01-23-1987')`
  );
} catch (err) {
  console.log(err);
}

const db = await getDB();
const dbGetAsync = util.promisify(db.get);

async function get(service) {
  let sql = `SELECT Id id, Service service, Date date FROM services WHERE service  = ?`;

  try {
    const row = await dbGetAsync(sql, [service]);
    let this_row = { row: row.id, service: row.service };
    this_row
      ? console.log(row.id, row.service, row.date)
      : console.log(`No service found with the name ${service}`);
    return row;
  } catch (err) {
    console.error(err.message);
  }
}

let row = await get("blah");

exports.get = get;

我收到此错误是因为我使用的是旧 Node 版本 (8.17.0),将 Node 更新到较新版本 (12.14.0) 修复了此错误。

getDB is an async function returning a Promise, so you have to await for the promise to resolve or chain a then to use its returned value: getDB 是一个返回 Promise 的异步函数,因此您必须await承诺解析或链接then才能使用其返回值:

// you have to put it inside an async function
const db = await getDB();
const dbGetAsync = util.promisify(db.get);
getDB().then(function(db){
  return util.promisify(db.get);
}).then(function(getFunction){
  // use get
})

Use await before getDB() as it is return promise, so that is why you are getting error.在 getDB() 之前使用await ,因为它是返回承诺,所以这就是您收到错误的原因。 see the correction below:请参阅以下更正:

const db = await getDB();
const dbGetAsync = util.promisify(db.get);

Also you have to wrap await inside async function other it won't work like this:此外,您必须将 await 包装在 async 函数中,否则它不会像这样工作:

(async function(){
  let bar = await foo();
})()

ERR_INVALID_ARG_TYPE is internal Node.js error. ERR_INVALID_ARG_TYPE 是内部 Node.js 错误。 It means that your code may invoke build-int function with wrong arguments.这意味着您的代码可能会使用错误的 arguments 调用 build-int function。

I've faced same error (ERR_INVALID_ARG_TYPE) but with much simpler code and in different circumstances.我遇到了同样的错误 (ERR_INVALID_ARG_TYPE),但代码更简单,而且在不同的情况下。

const readFileAsync = util.promisify(fs.readFile);
const readDirAsync = util.promisify(fs.readdir);

Reason was that fs.readFile and fs.readdir were both undefined.原因是 fs.readFile 和 fs.readdir 都未定义。 If you call util.promisify with undefined then Node.js produce a error ERR_INVALID_ARG_TYPE.如果您使用未定义的方式调用 util.promisify,则 Node.js 会产生错误 ERR_INVALID_ARG_TYPE。

In my case reason was that unit test was mocking build-in fs module and some of dependencies were initialized with 2 lines of code above.在我的例子中,原因是单元测试是 mocking 内置 fs 模块,一些依赖项是用上面的两行代码初始化的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError [ERR_INVALID_ARG_TYPE]:“侦听器”参数的类型必须为 function。接收未定义 - TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received undefined TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。 收到未定义和代码:'ERR_INVALID_ARG_TYPE' - TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined and code: 'ERR_INVALID_ARG_TYPE' TypeError [ERR_INVALID_ARG_TYPE]:“原始”参数必须是 function 类型 - TypeError [ERR_INVALID_ARG_TYPE]: The “original” argument must be of type function 接收 UnhandledPromiseRejectionWarning:TypeError [ERR_INVALID_ARG_TYPE]:“原始”参数必须是 function 类型 - Receiving UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type function 图片上传错误:TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。 接收类型未定义 - Image Upload Error: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined 'TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。 接收类型未定义' - 'TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined' 类型错误 [ERR_INVALID_ARG_TYPE]:“文件”参数必须是字符串类型。 接收类型对象 - TypeError [ERR_INVALID_ARG_TYPE]: The "file" argument must be of type string. Received type object TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。 收到 Object 的实例 - TypeError [ERR_INVALID_ARG_TYPE]: The “path” argument must be of type string. Received an instance of Object 等待 dTypeError [ERR_INVALID_ARG_TYPE]:“id”参数必须是字符串类型。 收到未定义 - Waiting for the dTypeError [ERR_INVALID_ARG_TYPE]: The “id” argument must be of type string. Received undefined Webpack 类型错误&#39;TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。 接收类型布尔值(真)&#39; - Webpack type error 'TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type boolean (true)'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM