Javascript: From Promises to Async/Await

  • 时间:2020-09-17 11:25:43
  • 分类:网络文摘
  • 阅读:81 次

What are Promises in Javascript? and what are the async/await? If you are using Javascript, these technologies are something that you don’t want to miss.

Christmas Tree Code

Let’s take a look at the following code, where we use callbacks and that unavoidably make the code ugly, as code are nested inside each other.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function asyncMethod(message, counter, cb) {
    setTimeout(function() {
        console.log(message + " " + counter);
        cb(counter + 1);
    }, 500);
}
 
asyncMethod("A", 1, (x) => {
        asyncMethod("B", x, (x) => {
            asyncMethod("C", x, (x) => {
                asyncMethod("D", x, (x) => { });
            })
        })
    }
);
function asyncMethod(message, counter, cb) {
    setTimeout(function() {
        console.log(message + " " + counter);
        cb(counter + 1);
    }, 500);
}

asyncMethod("A", 1, (x) => {
        asyncMethod("B", x, (x) => {
            asyncMethod("C", x, (x) => {
                asyncMethod("D", x, (x) => { });
            })
        })
    }
);

It will print the following messages one after another with 500ms interval:

1
2
3
4
A 1
B 2
C 3
D 4
A 1
B 2
C 3
D 4

The counter 1 is passed and every callback increments one. The Christmas tree code are not easy to maintain and they are simply ugly.

Using Promises

A Promise takes a function in its constructor. And the function takes two parameters: the fulfill and the reject. The fulfill is the callback when it is done and the reject is used when some error occurs.

1
2
3
4
5
6
7
8
function asyncMethod(message, counter) {
    return new Promise((fullfill, reject) => {
        setTimeout(function() {
            console.log(message + " " + counter);
            fullfill(counter + 1);
        }, 500);
    });
}
function asyncMethod(message, counter) {
    return new Promise((fullfill, reject) => {
        setTimeout(function() {
            console.log(message + " " + counter);
            fullfill(counter + 1);
        }, 500);
    });
}

Then, we can rewrite the above Christmas code, using the then() function which takes two parameters: the fulfill() and the reject().

1
2
3
4
5
6
7
8
asyncMethod("A", 1).then((x, err) => {
    asyncMethod("B", x).then((x, err) => {
        asyncMethod("C", x).then((x, err) => {
            asyncMethod("D", x).then((x, err) => {});
            })
        })
    }
);
asyncMethod("A", 1).then((x, err) => {
    asyncMethod("B", x).then((x, err) => {
        asyncMethod("C", x).then((x, err) => {
            asyncMethod("D", x).then((x, err) => {});
            })
        })
    }
);

It is just simply using the then to use the Promise, but the chain is still nested. However, we can separate the calls in its own functions. Then we can chain the Promise using then like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function A(counter) {
    return asyncMethod("A", counter);
}
 
function B(counter) {
    return asyncMethod("B", counter);
}
 
function C(counter) {
    return asyncMethod("C", counter);
}
 
function D(counter) {
    return asyncMethod("D", counter);
}
 
A(1).
  then(B).
  then(C).
  then(D);
function A(counter) {
    return asyncMethod("A", counter);
}

function B(counter) {
    return asyncMethod("B", counter);
}

function C(counter) {
    return asyncMethod("C", counter);
}

function D(counter) {
    return asyncMethod("D", counter);
}

A(1).
  then(B).
  then(C).
  then(D);

The code does now look much cleaner!

Converting Promises to Async/Await

The ES6 Javascript allows us to use a much cleaner syntax sugar: async/await. The async keyword is a function modifier that tells the Javascript that we can use the await keyword in the function to wait for some functions.

1
2
3
4
5
6
(async function test() {
    const A = await asyncMethod("A", 1);
    const B = await asyncMethod("B", A);
    const C = await asyncMethod("C", B);
    const D = await asyncMethod("D", C);
})();
(async function test() {
    const A = await asyncMethod("A", 1);
    const B = await asyncMethod("B", A);
    const C = await asyncMethod("C", B);
    const D = await asyncMethod("D", C);
})();

As the asyncMethod returns a promise, and when it is fulfilled, the counter will be incremented by one, we then can pass it (chain) into next one. The await will make sure that the function is either fulfilled or rejected before moving to next function call.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
冬季吃火锅大有门道 火锅底料很重要  寒冷天气吃多了这5类食物会伤及肠胃  萝卜的3种吃法可以防治冬季常见病  食品之辟谣系列:喝豆浆易患乳腺癌  食品之辟谣系列:忽悠美容丰胸减肥的食物  冬季预防食物中毒及中毒后急救措施  四种常见的食物可以排出身体毒素  男人多吃一些香蕉对身体大有好处  冬至时节常吃6种传统食物可补阳防寒  南方黑芝麻糊大肠菌群超标 5批次产品不合格 
评论列表
添加评论