简体   繁体   中英

Resolve a function that uses Promise

I have the following async function

export default async function getUserNames(id: string[]): Promise<string[]> {
    let userNames: string[] = [];
    // We do some stuff here like calling a service, etc...

    return userNames;
}

On a different typescript file, I am importing the getuserNames function and trying to call it like this:

const promiseResult = getUserNames(idList)
        .then(result => {
            return result;
        })
        .catch(error => {
            return undefined;
        });

    if (promiseResult) {
        // Do something else here.
    }

However, the promiseResult type is of Promise instead of string[] which is what I am expecting. How can I call the getuserNames function and when it is done, the actual string[] is returned to the promiseResult variable?

EDIT Is it accepted to do something like this?

let varB: string[];
const promiseResult = getUserNames(idList)
        .then(result => {
            varB = result;
        })
        .catch(error => {
            varB = undefined;
        });

if (varB) {
        // Do something else here.
    }

Lastly, please notice that the function that calls getUserNames is not defined as async and I can't change that.

If you want to get access to the value that the promise resolves to, your only options are

1) use the promise's .then callback

getUserNames(idList)
  .then(result => {
    // Do something else here.
  })

2) Put the code in an async function and use the await keyword:

async function someFunction () {
  const result = await getUserNames(idList);
  // Do something else here.
}

Note that since all async functions return promises, someFunction will return a promise in this example.

getUserNames does return a promise<string[]> that's exactly what its signature says.

You should perform your if (result) inside the then

Or you could use the new await keyword which will make sure the promise is resolved before it's assigned to promiseResult In this case, wrap your await inside a try/catch.

You not need to use async/await in your code.

/**
 * async data fetcher
 * @param {String} url 
 * @param {Object} options 
 * @returns {Promise}
 */
const fetch = (url, options) => {
  return new Promise((resolve, reject) => {
    fetch(url, options)
      .then((response) => {
        if (response.ok) {
          return resolve(response.json)
        }
        return reject(response.json)
      })
      .catch((error) => reject({ error }))
  })
}

/**
 * async fetch wrapper, returns a Promise
 * @param {NUmber} id 
 * @returns {Promise}
 */
const getUserNames = (id) => {
  return fetch('www.yourapi.com/get_user_names', { params: { id } })
}

const idList = [1, 2, 3]
// so, your code also will be asyncronious too:
Promise.all([getUserNames(idList)]).then((promiseResult) => {
  if (promiseResult) {
    // Do something else here.
  }
})

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