我是 JavaScript 新手,正在积极学习。我正在调用一个方法,该方法使用 await 关键字从 ES2016 类的异步方法中返回一个 promise :
export default class MyClass extends Model {
async getReport() {
const value = await xlsx.save(await this._getReportFileName());
console.log('await keyword returned method value');
console.log(`The value is: ${value}`);
return true;
}
}
谁能找出方法在有机会执行其逻辑之前和调用 resolve 之前执行的原因。 await 关键字似乎没有等待实际返回的 promise ,并且输出到控制台的值是未定义的。
对象 xlsx 是类 File 的一个实例,它有一个保存方法:
export default class File {
save(filename, options) {
writer.save(this, filename, options);
}
}
下面是调用保存辅助方法的代码:
function save(xlsx, filename, options) {
return new Promise((resolve, reject) => {
try {
const stream = fs.createWriteStream(filename, options);
const zip = archiver('zip');
stream.on('close', () => {
console.log('Resolving promise');
resolve();
});
stream.on('error', (err) => {
console.log('Rejecting promise');
reject(err);
});
zip.pipe(stream);
const file1 = 'fixtures/file1.txt';
const file2 = 'fixtures/file2.txt';
zip
.append(fs.createReadStream(file1), {
name: 'file1.txt'
})
.append(fs.createReadStream(file2), {
name: 'file2.txt'
})
.finalize();
} catch (error) {
console.log('Error when saving');
reject(error);
}
});
}
难道在监听流事件的范围内 resolve() 甚至不可访问/不可用?如果是这样,如何在监听流事件时正确解决 promise ?
最佳答案
您的 save(filename, options)
传递方法不是异步的,它不会从 save(xlsx, filename, options)
方法返回 promise 。
试试这个:
export default class File {
async save(filename, options) {
await writer.save(this, filename, options);
}
}
或者这个:
export default class File {
save(filename, options) {
return writer.save(this, filename, options);
}
}
关于javascript - 尽管使用 await 关键字,方法返回的 promise 没有完全执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40429442/