[英]Resolve a function that uses Promise
我有以下異步功能
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類型是Promise而不是string [],這正是我所期待的。 如何調用getuserNames函數,何時完成,實際的字符串[]將返回到promiseResult變量?
編輯是否接受這樣的事情?
let varB: string[];
const promiseResult = getUserNames(idList)
.then(result => {
varB = result;
})
.catch(error => {
varB = undefined;
});
if (varB) {
// Do something else here.
}
最后,請注意調用getUserNames的函數未定義為async,我無法更改。
如果您想要訪問promise所解決的值,那么您唯一的選擇就是
1)使用promise的.then回調
getUserNames(idList)
.then(result => {
// Do something else here.
})
2)將代碼放在異步函數中並使用await關鍵字:
async function someFunction () {
const result = await getUserNames(idList);
// Do something else here.
}
請注意,由於所有異步函數都返回promises,因此someFunction將在此示例中返回promise。
getUserNames
確實返回了一個promise<string[]>
,這正是它的簽名所說的。
您應該在then
執行if (result)
或者您可以使用新的await
關鍵字,它將確保在將promise分配給promiseResult
之前promiseResult
在這種情況下,將await
包裝在try / catch中。
您不需要在代碼中使用async / await。
/**
* 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.
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.