异步函数返回Promise {< pending>}? [英] async function returns Promise { <pending> }?
问题描述
我具有以下异步功能:
async function readFile () {
let content = await new Promise((resolve, reject) => {
fs.readFile('./file.txt', function (err, content) {
if (err) {
return reject(err)
}
resolve(content)
})
})
console.log(content)
}
readFile()
这很好.它将文件缓冲区按预期输出到控制台.但是现在,如果我尝试返回值:
This runs just fine. It outputs the file buffer to the console as expected. But now, if I try to instead return the value:
async function readFile () {
let content = await new Promise((resolve, reject) => {
fs.readFile('./file.txt', function (err, content) {
if (err) {
return reject(err)
}
resolve(content)
})
})
return content
}
console.log(readFile())
我现在得到:
Promise { <pending> }
这是为什么?为什么可以在该函数内使用一个值,但是当您从该函数中将其返回时,它现在却是一个Promise?
Why is this? Why can you use a value inside that function but when you return it out of the function it's now a Promise?
您如何在正常的工作流程中实际使用此功能?例如,假设我要检查文件是否存在,然后读取文件,然后使用内容更新一些数据库,同步伪代码将如下所示:
How do you actually make use of this in a normal workflow? For example, lets say I wanted to check if a file exists, then read in the file, then update some database with the content, the synchronous pseudo code would look something like this:
if (fileExists(path)) {
buffer = readFile(path)
updateDatabase(buffer)
}
该工作流程由3个独立的异步操作组成.您如何使用 async/await
做这样的事情?是将整个脚本包装在 async
函数中的键吗?
That workflow consists of 3 individual async operations. How would you do something like this with async/await
? Is the key that you have to have your entire script wrapped in an async
function?
async function doSomething () {
if (fileExists(path)) {
buffer = readFile(path)
updateDatabase(buffer)
}
}
(请记住,这只是伪代码,但希望能引起我的注意).
(Keep in mind that is just pseudo-code but hopefully its gets my point across).
推荐答案
所有 async
函数均返回承诺,如注释中所述.因此,您可以像这样重新编写 readFile
函数:
All async
functions return a promise as was mentioned in the comments. You could therefore re-write your readFile
function like this:
function readFile() {
return new Promise((resolve, reject) => {
fs.readFile('./file.txt', function (err, content) {
if (err) {
return reject(err)
}
resolve(content)
})
})
}
然后您将通过 await
使用 readFile
的返回值:
You would then consume the return value of readFile
via await
:
console.log(await readFile()) // will log your actual file contents.
这种范例的通常工作流程是将异步操作分解为单独的函数,每个函数都返回一个Promise,然后在更广泛的 async
函数中运行它们,就像您建议的那样,但是使用 await
s和一些错误处理,例如:
The usual workflow with this paradigm is to break your async operations into separate functions that each return a promise, and then run them all inside a broader async
function, much like you suggest, but with await
s and some error handling like so:
async function doSomething () {
try {
const fileCheck = await fileExists(path)
if (fileCheck) {
const buffer = await readFile(path)
await updateDatabase(buffer)
// Whatever else you want to do
}
} catch (err) {
// handle any rejected Promises here.
}
}
这篇关于异步函数返回Promise {< pending>}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!