Writing in the front

Unable to sleep at night, I decided to get up and ask a friend async&await question during the day’s work. In fact, I had always wanted to write something about this problem, but I was too lazy to do anything about it. Today still can’t help but want to vomit bad once, if have what to say wrong, welcome the criticism finger-pointing!

Problems with asynchronous functions in front-end projects

Nowadays front-end projects are full of such a large number of asynchronous operations. Due to the rise of async & await, TODAY I saw my friend’s project code is full of try catch. The code is roughly as follows:

function request(type) {
    return new Promise((resolve, reject) = > {
        setTimeout(() = > {
            type === 'a' ? resolve('resolve') : reject('reject')},2000); })}async function getData() {
    try {
        let ret1 = await request('a');
    }catch(error){
        // todo 
    }

    try {
        let ret2 = await request('b');
    } catch (error) {
        // todo
    }

    try {
        let ret3 = await request('c');
    } catch (error) {
        // todo
    }
}
getData();
Copy the code

The solution

I can’t stand a lot of try catches in a complex business. Something must be done to solve the problem. First, we need to make it clear that the promise after await must be a resolve state to get the result correctly. To resolve this problem, async must return a resolve state, but errors cannot be ignored. Combined with nodeJS error first, we can return errors and results as an array, and we have the following code:

/** * Advanced processing that accepts a promise and returns a resolve promise@param {*} promise 
 */
const hRequest = promise= > promise.then(res= > [undefined, res]).catch(err= > [err,undefined])


async function getData2() {
    let err,result;
    [err,result] = await hRequest(request('a'));
    console.log(err,result);
    [err,result] = await hRequest(request('b'));
    console.log(err,result);
}
getData2();
Copy the code

The last

After this transformation, you can first determine whether there is an error, and then deal with your business.