The async await method is particularly useful, but when encountering an exception, it is very time-consuming and laborious to manually try catch one after another. Besides, it is easy to forget and cause errors. Here we summarize two methods to solve this problem.

Method one: encapsulate yourself

Method definition

function to(promise) {
    if(! promise || !Promise.prototype.isPrototypeOf(promise)) {
        return new Promise((resolve, reject) = > {
            reject(new Error('Parameter must be promise'));
        }).catch((err) = > {
            return [err, null];
        });
    }
    return promise.then(data= > {
        return [null, data];
    }).catch(err= > {
        return [err, null];
    });
}
Copy the code

How to use

async function f() {
    const [error, data] = awaitto(...) ;if(error){ ... }... }Copy the code

Method 2: Third-party libraries

await-to-js

Method of use

import to from 'await-to-js';

Copy the code