Using Generator and Promise in Javascript to avoid callback hell

 How do you avoid Callback Hell in Javascript ? 

How to make the asynchronous code "look like" synchronous code in Javascript ?

Using Promise of Javascript is not enough

With Promise and Generator function, you can make you async code "look like" sync code




var callApiFirstName = (firstName) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('This is FirstName ' + firstName);
        }, 3000);
    })
}
var callApiMidName = (midName) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('This is MidName ' + midName);
        }, 2000);
    })
}
var callApiLastName = (lastName) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('This is ' + lastName);
        }, 1000);
    })
}

function* logic(firstName, midName, lastName) {
    var str1 = yield callApiFirstName(firstName);
    console.log(str1);
    var str2 = yield callApiMidName(midName);
    console.log(str2);
    var str3 = yield callApiLastName(lastName);
    console.log(str3);
}

function executeAsync (asyncLogic, ...params) {
    var generatorLogic = asyncLogic(...params);
    var res = generatorLogic.next();
    _recursive(generatorLogic, res);
    
}

function _recursive(generatorLogic, res) {
    if (res.done) {
        return;
    } else {
        res.value.then((result) => {
            var nextRes = generatorLogic.next(result);
            _recursive(generatorLogic, nextRes);
        });
    }
}
executeAsync(logic, 'tan', 'van', 'nguyen');

You can view the result of code above:




Nhận xét

Bài đăng phổ biến từ blog này

TypeORM should using repository or query buider ?

Type of children prop in React Typescript

MSAL: Difference between Public Client Application And Confidential Client Application