nodejs how to return the desired value from the asynchronous callback

const fs = require('fs')

let read=()=>{
    fs.readFile("./contents/test.json",(err,data)=>{
        return JSON.parse(data.toString())
    })
}

(()=>{
    let result = read()
    console.log(result)  //undefind
})()

We want to return a value we want from a callback function, according to the wording of the above we can always get undefind.

The solution is very simple, as follows.

const fs = require('fs')

let read=async ()=>{
    return new Promise((resolve,reject)=>{
        fs.readFile("./contents/test.json",(err,data)=>{
            if(err) reject(err)
            resolve(JSON.parse(data.toString()))
        })
    })

}

(async ()=>{
    let result =await read()
    console.log(result)    //{msg:"ok"}
})()

Incidentally, the asynchronous problem solved.

Guess you like

Origin www.cnblogs.com/BlackFungus/p/12329550.html