reactjs 我如何从promise更改为async/await?

carvr3hs  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(162)

如何在google驱动器集成中将我代码中的箭头函数更改为async/await语法。

const listFiles = () => {
    setLoading(true)
    gapi.client.drive.files
        .list({
            pageSize: 500,
            fields: 'nextPageToken, files(id, name, mimeType, modifiedTime)',
        })
        .then(function (response) {
            setLoading(false)
            const res = JSON.parse(response.body);
            setDocuments(res.files);

        });
};

我想添加另一个函数async/await:

const initClient = () => {
    setLoading(true)

    gapi.client
      .init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES,
      })
      .then(
        function () {
          setConnectStorage(true);
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
          setLoading(false)
        },
        function (error) {
          alert(error)
        }
      );
  };
kuuvgm7e

kuuvgm7e1#

const listFiles = () => {
  setLoading(true)
  return new Promise((resolve, reject) => {
    gapi.client.drive.files
        .list({
            pageSize: 500,
            fields: 'nextPageToken, files(id, name, mimeType, modifiedTime)',
        })
        .then(function (response) {
            setLoading(false)
            const res = JSON.parse(response.body);
            resolve(res.files)
        });
  })
};

const initClient = () => {
  setLoading(true)
  return new Promise ((resolve, reject) => {
    gapi.client
      .init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES,
      })
      .then(
        function () {
          setConnectStorage(true);
          // gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
          // updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
          resolve({status: gapi.auth2.getAuthInstance().isSignedIn.get()})
          setLoading(false)
        },
        function (error) {
          reject({status: false})
        }
      );
  })
};

然后运行这些函数:

(async () => {
  const files = await listFiles()
  const status = await initClient()
})()

相关问题