构造并返回一组返回的诺言

时间:2019-09-04 13:05:31

标签: javascript promise return

我有以下函数,该函数实质上调用了其他三个基于promise的函数。所有的承诺似乎都在起作用,但是我无法获得返回tableData数组的函数。

任何指针都将非常有帮助。

function getALLBooks() {

  tableData = []

  getAPIKey(creds)
  .then(apikey => {
  //  console.log(apikey)
    getBooks(apikey).then(books => {
    //  console.log(books)
      books.forEach(function (value) {
     //  console.log(value.Guid);
       getBook(apikey, value.Guid).then(book => {
     //    console.log(apikey)
     //    console.log(book)
          console.log(book.Name)
         tableData.push({
          "name": book.Name
         })
       })
       
     });
     return tableData
    })
  })
  .catch(error => {
    console.log(error)
  })
}

getALLBooks()

3 个答案:

答案 0 :(得分:1)

我建议兑现承诺:

  getAPIKey(creds).then(apikey => {
     return getBooks(apikey).then(books => {
        return Promise.all(books.map(value => getBook(apikey, value.Guid)));
     });
  }).then(tableData => {
     // do something wit array of data
  });

答案 1 :(得分:1)

首先,使用异步/等待或链接您的诺言, async/await在语法上更简单。

async function getALLBooks() {

  tableData = [];
  try{
    const apikey  = await getAPIKey(creds);
    const books = await getBooks(apikey);
    const booksPromise = [];
    books.forEach(function (value) {
      booksProm.push(getBook(apikey, value.Guid));
    }
    const tableData = await booksPromise;
  }catch(err){
    console.log("error thrown by first await");
    throw err;
  }
}

getALLBooks.then(tableData => {
  console.log(tableData)
}).catch(err => {
  console.log(err);
})

为什么您的代码段未提供期望的结果,

function getALLBooks() {

  tableData = []

  getAPIKey(creds)
  .then(apikey => {
   /* At this point, when your control reaches here the following getBooks() function is called asynchronously and hence tableData ie empty array is returned as fulfilled value */
   getBooks(apikey).then(books => {
    //  console.log(books)
      books.forEach(function (value) {
     //  console.log(value.Guid);
       getBook(apikey, value.Guid).then(book => {
     //    console.log(apikey)
     //    console.log(book)
          console.log(book.Name)
         tableData.push({
          "name": book.Name
         })
       })

     });
       /*this is returned before your getBooks() operation actually starts.*/
      return tableData
    })
  })
  .catch(error => {
    console.log(error)
  })
}

答案 2 :(得分:1)

git commit