[英]Actionhero actions returning immediately
我试图了解ActionHero异步/等待的核心概念,并且碰壁很多。 本质上,在一个动作中,为什么返回立即返回,而不是在500ms之后返回?
async run (data) {
setTimeout(() => data.response.outcome = 'success',500)
}
澄清编辑:这个问题更多的是关于异步执行流和承诺实现,而不是setTimeout()的字面使用。 它并不是真的专用于ActionHero,而是AH使用的模式,这是我第一次接触这些概念。 提供的答案阐明了某些功能必须包装在一个Promise中,以便可以等待它们,并且有多种方法可以做到这一点。
因为您没有等待它完成。
基本上,您需要等待setTimeout。
async run (data) {
await setTimeout(() => data.response.outcome = 'success',500)
}
但这不起作用,因为setTimeout不是一个承诺
您可以使用一个简单的睡眠功能,该功能会在一段时间后解决。
async function sleep (time) {
return new Promise(resolve => setTimeout(resolve, time));
}
async function run (data) {
await sleep(500);
data.response.outcome = 'success';
}
就像setTimeout(可以作为回调api一样)可以做成promise一样,流也可以做成promise。 请注意在sleep和readFile示例中,我仅使用async关键字来使情况更清楚
async readFile (file) {
return new Promise((resolve, reject) => {
let data = '';
fs.createReadStream(file)
.on('data', d => data += d.toString())
.on('error', reject)
.on('end', () => resolve(data));
});
}
对于大多数功能,您可以跳过手动承诺,而使用util.promisify
const { readFile } = require('fs');
const { promisify } = require('util');
const readFileAsync = promisify(readFile);
关键部分是承诺应在工作完成后解决,并且您应使用await
或.then
等待它
例如,为了使事情更清楚,第一个例子
async function run (data) {
return sleep(500).then(() => data.response.outcome = 'success';);
}
乃至
function run (data) {
return sleep(500).then(() => data.response.outcome = 'success';);
}
在运行时都一样
所以完成
async function transform (inputFile, targetWidth, targetHeight) {
return new Promise((resolve, reject) => {
let transformer = sharp()
.resize(targetWidth, targetHeight)
.crop(sharp.strategy.entropy)
.on('info', { width, height } => console.log(`Image created with dimensions ${height}x${width}`)
.on('error', reject)
.on('end', resolve);
inputFile.pipe(transformer);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.