Get data using await async without try catch

后端 未结 5 1813
抹茶落季
抹茶落季 2020-12-15 02:11

I am trying to use await-async without try-catch for this:

<
5条回答
  •  再見小時候
    2020-12-15 02:33

    If you have such above single line async/await function, then this would have been clean code for you:

    const getUsers = async (time, shouldReject=false) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            if (shouldReject) {
              reject(Error('Rejected...'));
            } else {
              resolve(["User1", "User2"]);
            }
          }, time);
        });
    }
    
    const userOperation = users => {
      console.log("Operating user", users);
    }
    
    // Example 1, pass
    getUsers(100)
        .then(users => userOperation(users))
        .catch(e => console.log(e.message));
    
    // Example 2, rejected
    getUsers(100, true)
        .then(users => userOperation(users))
        .catch(e => console.log(e.message));

    And for multiple await in a single async function, it would good to have try/catch block as below:

    const users = async () => {
        try {
            const value = await getUsers(1000, false);
            const value1 = await getUsers2(1000, false);
            ...
        } catch (error) {
            ...
        }
    }
    

提交回复
热议问题