从回调nodejs外部调用变量

calling a variable from outside a callback nodejs

我使用来自 npm 的 glob

gl = require("glob");
get = {};
gl("path/to/files/*.rmd", {}, function(err, files){
     get.files = files
 });
console.log(get.files)

output: undefined

我想做的是从其回调外部访问文件。但是,我尝试的一切都不起作用。

从内部函数引用外部变量是完全可以接受的,这就是 JS 如此特别的原因。这叫做闭包。

但问题是 globasynchronous,这意味着它将 运行 console.log 在完成实际的 glob 搜索之前。

所以你可以做的是 console.log 它在回调中。或者在 then 函数中用它和 console.log 做出承诺。或者您可以使用 async/await 并等待函数。

const gl = require("glob");
const get = {};
gl("./*.js", {}, function(err, files){
     get.files = files
     console.log(get);
});
// OR
const glP = function(){
    return new Promise((res, rej)=>{
        gl("./*.js", {}, function(err, files){
            if(err) rej(err);
            res(files);
       });
    })
}

glP()
.then((files)=>{
    get.files = files;
    console.log(get);
})

// OR
(async ()=>{
    const files = await glp();
    get.files = files;
    console.log(get);
})

使用glob.sync可用于同步调用

gl = require("glob");
let get = {};
get['files']=gl.sync("path/to/files/*.rmd", {});
console.log(get.files)

参考:sync call glob.sync

由于 async 回调的性质,您的 console.log(get.files) 将在调用 glob() 的回调函数之前被调用。楼上的回答都很好。我要再添加一个答案。

'use strict';

const glob = require('glob');
const bluebird = require('bluebird');

const globPromise = bluebird.promisify(glob);
let get = {};
globPromise("./files/*.rmd", {})
  .then((files) => {
    console.log(files);
    get.files = files;
    console.log(get.files);
  });

以上代码 Promisify 整个 glob NPM 包并为您提供了执行异步任务的能力。在您自己的代码中,您应该在回调函数中编写 console.log() ,或者您可以使用 Promises 来确保一旦 glob 完成它的工作就会被调用。