關(guān)鍵:
??要解決這個(gè)問題的關(guān)鍵就是await function()
中function()的返回值是什么類型?
答案:
??Promise
案例:
??下面給出一個(gè)案例液荸,以流的形式讀取文件數(shù)據(jù)。例子中定義了一個(gè)readStreamFile函數(shù),然后在main中使用await調(diào)用readStreamFile這個(gè)方法鼻百。將文件內(nèi)容賦值給file_content變量.
const readStreamFile = (filename) => {
return new Promise((executor, reject) => {
let chunks = [];
const reader = fs.createReadStream(filename)
reader.on('data', (chunk) => {
chunks.push(chunk);
})
reader.on('end', () => {
reader.close();
executor(Buffer.concat(chunks).toString('base64'));
})
reader.on('error', (err) => {
reject(err);
})
})
}
const main = async (filename) => {
try {
const file_content = await readStreamFile(filename);
} catch (e) {
console.log(e.message);
}
}
main("filename");