[英]How can I get the value of a async and pass to a function?
I need to get the value of mtime and return as result of lastSave function but i get undefined.我需要获取 mtime 的值并作为 lastSave function 的结果返回,但我没有定义。 I know I can use fs.statSync("./Data.xlsx") to get this value.我知道我可以使用 fs.statSync("./Data.xlsx") 来获取这个值。 I'm using fs.stat() as example for async inside a function.我使用 fs.stat() 作为 function 中的异步示例。
const lastSave = async (file) => {
const momento = await fs.stat(file, function (err, stats) {
var mtime = stats.mtime;
console.log("interno", mtime); // this works
return mtime
});
return momento
}
console.log(lastSave('./Data.xlsx')) // this writes "undefined"
Use the sync variant of the function.使用 function 的同步变体。
const fs = require('fs');
const lastSave = file => {
return fs.statSync(file).mtime;
}
console.log(lastSave('./Data.xlsx'));
If there is no sync version wrap the call in a async function and call it:如果没有同步版本,则将调用包装在异步 function 中并调用它:
const fs = require('fs');
const lastSave = file => {
return new Promise(done => fs.stat(file, function (err, stats) {
var mtime = stats.mtime;
console.log("interno", mtime); // this works
done(mtime);
}));
}
(async () => {
console.log(await lastSave('./Data.xlsx'));
})();
You can use the promise-based variant:您可以使用基于承诺的变体:
const fs = require('fs/promises');
const lastSave = async file => {
return (await fs.stat(file)).mtime;
}
(async () => {
console.log(await lastSave('./Data.xlsx'));
})();
Alternatively you can promisify your async function:或者,您可以承诺您的异步function :
const fs = require('fs');
const util = require('util');
const lastSave = async file => {
return (await util.promisify(fs.stat)(file)).mtime;
}
(async () => {
console.log(await lastSave('./Data.xlsx'));
})();
Alternatives for替代品
(async () => {
console.log(await lastSave('./Data.xlsx'));
})();
are是
lastSave('./Data.xlsx').then(console.log);
and和
lastSave('./Data.xlsx').then(result => { console.log(result); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.