我有以下异步函数
export default async function getUserNames(id: string[]): Promise<string[]> {
let userNames: string[] = [];
// We do some stuff here like calling a service, etc...
return userNames;
}在另一个类型记录文件中,我导入了getuserNames函数,并试图这样调用它:
const promiseResult = getUserNames(idList)
.then(result => {
return result;
})
.catch(error => {
return undefined;
});
if (promiseResult) {
// Do something else here.
}然而,promiseResult类型是有希望的,而不是我所期望的string[]。我如何调用getuserNames函数,当它完成时,实际的string[]返回给promiseResult变量?
编辑是接受做这样的事情吗?
let varB: string[];
const promiseResult = getUserNames(idList)
.then(result => {
varB = result;
})
.catch(error => {
varB = undefined;
});
if (varB) {
// Do something else here.
}最后,请注意,调用getUserNames的函数没有定义为异步,我无法更改它。
发布于 2019-03-27 17:16:30
您不需要在代码中使用异步/等待。
/**
* 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.
}
})https://stackoverflow.com/questions/55382802
复制相似问题