nodejs express中間部品の非同期フィードバック、koa中間部品のasync awaitの未来動向
14380 ワード
jsはシングルスレッドで、非同期で多プロセスを実現します.
async await
async await :1. await promise , resolve 2. await async 3. async promise 4. try-catch promise reject
const fs = require('fs') //nodejs
const path = require('path') //nodejs
// callback
function getFileContent(fileName, callback) {
const fullFileName = path.resolve(__dirname, 'files', fileName)
// __dirname
fs.readFile(fullFileName, (err, data) => {
if (err) {
console.error(err)
return
}
callback(
JSON.parse(data.toString())
)
})
}
// callback-hell
getFileContent('a.json', aData => {
console.log('a data', aData)
getFileContent(aData.next, bData => {
console.log('b data', bData)
getFileContent(bData.next, cData => {
console.log('c data', cData)
})
})
})
// promise
function getFileContent(fileName) {
const promise = new Promise((resolve, reject) => {
const fullFileName = path.resolve(__dirname, 'files', fileName)
fs.readFile(fullFileName, (err, data) => {
if (err) {
reject(err)
return
}
resolve(
JSON.parse(data.toString())
)
})
})
return promise
}
// promise
getFileContent('a.json').then(aData => {
console.log('a data', aData)
return getFileContent(aData.next)
}).then(bData => {
console.log('b data', bData)
return getFileContent(bData.next)
}).then(cData => {
console.log('c data', cData)
})
async function readFileData() {
//
try {
const aData = await getFileContent('a.json')
console.log('a data', aData)
const bData = await getFileContent(aData.next)
console.log('b data', bData)
const cData = await getFileContent(bData.next)
console.log('c data', cData)
} catch (err) {
console.error(err)
}
}
readFileData()
async function readAData() {
const aData = await getFileContent('a.json')
return aData
}
async function test() {
const aData = await readAData() // promise
console.log(aData)
}
test()