Let us master asynchronous and synchronous in node.js together

Node.js asynchronous programming

Sync API

console.log(' before ');
setTimeout(function () {
    console.log("last");
}, 2000)
console.log('after');
/*  before 
after
last */

Asynchronous API

function getMsg() {
    
    
    setTimeout(function () {
    
    
        return {
    
    
            msg: 'hello node.js'
        }
    }, 2000)
}
const msg = getMsg();
console.log(msg); //undefined

Get the return value of the asynchronous API

You can use the callback function to

function getData(callback) {
    
    
    callback('123')
}

getData(function (n) {
    
    
    console.log(' callback函数被调用了') // callback函数被调用了
    console.log(n) //123
})

Simplify further

function getMsg(callback) {
    
    
    setTimeout(function () {
    
    
        callback({
    
    
            msg: 'hello node.js'
        })
    }, 2000)
}
const msg = getMsg(function (data) {
    
    
    console.log(data) //{ msg: 'hello node.js' }
});

The difference between synchronous API and asynchronous API execution order

Sync API

console.log('代码开始执行')
setTimeout(function () {
    
    
    console.log(' 2s ')
}, 2000)
setTimeout(function () {
    
    
    console.log('Os ')
}, 0)
console.log('代码结束执行')
/* 
代码开始执行
代码结束执行
Os 
2s  
*/

Asynchronous API

const fs = require('fs');
let promise = new Promise((resolve, reject) => {
    
    
    fs.readFile('./Node.js/async/14.txt', 'utf8', (err, result) => {
    
    
        if (err != null) {
    
    
            reject(err);
        } else {
    
    
            resolve(result);
        }
    });
});
promise.then((result) => {
    
    
    console.log(result)
}).catch(err => {
    
    
    console.log(err);
})

Use callback method to specify execution order

const fs = require('fs');
// 回调地狱
// fs.readFile('./Node.js/async/1.txt', 'utf8', (err, result1) => {
    
    
//     console.log(result1)
//     fs.readFile('./Node.js/async/2.txt', 'utf8', (err, result2) => {
    
    
//         console.log(result2)
//         fs.readFile('./Node.js/async/3.txt', 'utf8', (err, result3) => {
    
    
//             console.log(result3)
//         })
//     })
// });

function p1() {
    
    
    return new Promise((resolve, reject) => {
    
    
        fs.readFile('./Node.js/async/1.txt', 'utf8', (err, result) => {
    
    
            resolve(result)
        })
    });
}

function p2() {
    
    
    return new Promise((resolve, reject) => {
    
    
        fs.readFile('./Node.js/async/2.txt', 'utf8', (err, result) => {
    
    
            resolve(result)
        })
    });
}

function p3() {
    
    
    return new Promise((resolve, reject) => {
    
    
        fs.readFile('./Node.js/async/3.txt', 'utf8', (err, result) => {
    
    
            resolve(result)
        })
    });
}
// p1().then((r1) => {
    
    
//     console.log(r1);
// })
p1().then((r1) => {
    
    
        console.log(r1);
        return p2();
    })
    .then((r2) => {
    
    
        console.log(r2);
        return p3();
    })
    .then((r3) => {
    
    
        console.log(r3)
    })

Use the await promise keyword to further simplify the code

//1.在普通函数定义的前面加上async关键字普通函数就变成了异步函数
//2.异步函数默认的返回值是promise对象
//3.在异步函数内部使用throw关键字进行错误的抛出//
//await关键字
// 1.它只能出现在异步函数中
// 2.await promise 
// 它可以暂停异步函数的执行等待promise对象返回结果后再向下执行函数
 async function fn() {
    
    
    // throw '发生了一些错误';
    return 123;
    //console.log(fn()){
    
    
}
fn().then(function (data) {
    
    
    console.log(data);
}).catch(function (err) {
    
    
    console.log(err);
}) 

Use the async await keyword to make it simpler

async function p1() {
    
    
    return 1;
}
async function p2() {
    
    
    return 2;
}
async function p3() {
    
    
    return 3;
}
async function run() {
    
    
    let r1 = await p1();
    let r2 = await p2();
    let r3 = await p3();
    console.log(r1, r2, r3);
}
run();

Motivate today

I believe that no matter how bumpy the road in the future is, as long as you seize today, you will taste the sweetness of life in your struggle sooner or later. Seize every minute and every second of your life, better than a vain month and a year!

Guess you like

Origin blog.csdn.net/weixin_50001396/article/details/112208394
Recommended