[英]retrieving values from resolved Promise object
我試圖從一系列承諾中獲取值。
async function retrieveIssues() {
let rawdata = fs.readFileSync(argv.i);
let issues = JSON.parse(rawdata);
const issuesArray = issues.Issues;
const promises = issuesArray.map(issue => getIssueInfo(issue));
await Promise.all(promises);
// promises is now array of current issue information
console.log(promises)
console.log(promises[0])
}
所以我所擁有的是一組 Promise 對象,如下所示:
Promise {
{ title: 'Work',
body: 'We\'ve had...\n',
labels: [ [Object] ] } }
例如,我將如何訪問標題?
當您想使用等待的Promise.all
調用的結果時,您仍在使用promises
變量來嘗試訪問這些值。 例如:
const results = await Promise.all(promises);
// promises is now array of current issue information
console.log(results);
console.log(results[0]);
了解Promise.all
行為方式有助於了解如何處理Promise.all
。
如果沒有async/await
,您的代碼將如下所示:
Promise.all(promises).then(results => {
// results is now an array of current issue information
console.log(results)
console.log(results[0])
console.log(results[0].title)
})
當您使用await
,通常會在then
檢索的值被返回,因此您需要將其存儲在一個變量中並使用它。 因此你得到:
let results = await Promises.all(promises)
// results is now an array of current issue information
console.log(results)
console.log(results[0])
console.log(results[0].title)
您可以訪問標題為-
let promise = await Promise.all(promises);
console.log(promise[0].title);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.