I posted before about Asynchronous
and this time review first and then I'll check how callback value work in Javascript
maybe if you have a experience what do you click and during a date loading you can keep click or another act when you use internet.
for example, If you wait a video load(have some big length video what you have to wait..) in Youtube also you've been click another video or doing something at the same time. but although the first video not open yet, the system never wait a first video til' open just execution the click button right away.(it means you can do lots of things)
the reason why the program is Asynchronous.
Asynchronous isn't wait the work
but synchronous is wait til' send a response from server when make a request.
=> use callback in this time
callback return value exisit return null, doesn't exist value return not null
=> new Promise has resolve(), reject()
resolve() can handle for to do a next action.
reject() can hanlde for error.
위 코드와 비교 했을 때 가독성이 좋아짐.
first run printString("A") first
and then run .then() below blahblah
and you can handle the error last line in .catch
//for example
return getDataFromFilePromise(user1Path)
.then(user1 => { // user1 has user1Path return value
//**this is f*** important remember this**
//**this is f*** important remember this**
return getDataFromFilePromise(user2Path)
.then(user2 => { // user2 has user2Path return
//**this is f*** important remember this**
//**this is f*** important remember this**
return JSON.parse(`[${user1},${user2}]`); //
})
})
many return can sort like this.
=> you can also use Async & Await insted of Promise
Async & Await is new version.
you have to declare async first then you can use await
The result is the same with promise
https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_fs_readfile_path_options_callback
path <string> | <Buffer> | <URL> | <integer> filename or file descriptor
options <Object> | <string>
encoding <string> | <null> Default: null
flag <string> See support of file system flags. Default: 'r'.
callback <Function>
err <Error>
data <string> | <Buffer>
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
fs.readFile('/etc/passwd', 'utf8', callback);
//the option you can bring like Object
//*************************************//
let options = {
encoding: 'utf8', // open with 'UTF-8' set
flag: 'r' // 'to read' open option
}
fs.readFile('/etc/passwd', options, ...)
JSON.parse = the parameter need {} or String type
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Promise.all = the parameter need to arr !
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Reference
https://nodejs.org/dist/latest-v12.x/docs/api/
https://nodejs.org/dist/latest-v12.x/docs/api/dns.html //dns module
https://nodejs.org/dist/latest-v12.x/docs/api/fs.html //file system module