简体   繁体   中英

How can I use await fetch() in a promis so that it doesn't violate the eslint rule no-async-promise-executor?

My code is violating the eslint rule no-async-promise-executor but I'm not sure how to refactor it so that it doesn't have the async in the new Promise(async (resolve, reject) => {}); . My code is full of these and I guess it causes errors to bot be caught so I could use some help understanding how to approach this better.

Here's an exampe function:

updateUser = () => {
    return new Promise(async (resolve, reject) => {
        try {
            const url = "/getUser";
            const response = await fetch(url);
            if (response.ok) {
                const user = await response.json();
                //
                // Do something with user object...
                //
            } else {
                console.log("response", response);
                window.location = "/admin";
            }
            resolve();
        } catch (error) {
            console.log("error: ", error);
            reject(error);
        }
    });
};

async functions always return promises.

By wrapping your anonymous async function in new Promise(...) you are creating a Promise which only and always adopts the promise returned by the async function.

Just get rid of the wrapper, replace your resolve calls with return and your reject with throw .

updateUser = async () => {
    try {
        const url = "/getUser";
        const response = await fetch(url);
        if (response.ok) {
            const user = await response.json();
            //
            // Do something with user object...
            //
        } else {
            console.log("response", response);
            window.location = "/admin";
        }
    } catch (error) {
        console.log("error: ", error);
        throw error;
    }
};

when you mark the function as async, it will automatically wrap the return value inside a promise, whatever you return from the function... it will get passed to .then() and whatever is thrown inside a async function will get passed to your error handler such as .catch()

here is a example of what you could do.

const updateUser = async () => {
    const url = "/getUser";
    let response;

    try {
        response = await fetch(url);
    } catch (error) {
        throw new Error(error);
    }

    return response;
}

you can also reference the global promise explicit to return or reject values inside a async function.

const updateUser = async () => {
    const url = "/getUser";
    let response;

    try {
        response = await fetch(url);
    } catch (error) {
        Promise.reject(error);
    }

    return Promise.resolve(response);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM