0

我有一个在单击按钮时调用的函数,并且我试图在单击时通过 API 获取数据。下面是点击触发的函数。我必须通过 API 获取一次数据,然后根据获取的数据中的一个字段,我需要从另一个数据表中获取另一个数据。所以,我设计了我的编码如下,我的控制台看起来像这样:

控制台看起来像这样:

全部完成 []length: 0__proto__: Array(0)

1466(for循环期间记录的customer_id)

1663(for循环期间记录的customer_id)

我认为基于 promise 逻辑,所有完成的事情最后都应该被阅读,我在这里遗漏了什么吗?所以理想情况下,Alldone 控制台应该在最后调用包含基于 customer_ids 1466、1663 获取的数据。

我不确定我错过了什么,我是 javascript 以及堆栈溢出的新手,所以非常感谢详细的回答。

  function test(pmt_id, crm_supplier_id) {
  const url = 'http://127.0.0.1:8000/creditor-detail/'+pmt_id+'/supplier/'+crm_supplier_id+'/'
  let promises = [];

  const results = fetch(url)
  .then(resp => resp.json())
  .then(function (item) {

    var list = item;

    for (var i in list) {
      promises.push(getCustomer(list[i].customer_id));
      console.log(list[i].customer_id)

    }
  })
  
  Promise.all(promises)
      .then((results) => {
        console.log("All done", results);
      })
      .catch((e) => {
        
        console.log(err)
      });
}

//second function

function getCustomer(customer_id) {

return new Promise((resolve, reject) => {
  const url = 'http://127.0.0.1:8000/customer-detail/' + customer_id+ '/';
  fetch(url)
    .then(resp => resp.json())
    .then((item) => resolve(item))
    .catch
4

1 回答 1

2

Promise.all您甚至在将任何内容推入数组之前运行该部分promises,因为后者是异步运行的。您需要将Promises.all部件移动到.then

const results = fetch(url)
.then(resp => resp.json())
.then(function (item) {
  var list = item;
  for (var i in list) {
    promises.push(getCustomer(list[i].customer_id));
    console.log(list[i].customer_id)
  }
})
.then(() => Promise.all(promises))  
.then((results) => {
  console.log("All done", results);
})
.catch((e) => {
  console.log(err)
});

此外,只是编写.catch什么都不做,您需要调用它并传递一个处理程序:

fetch(url)
  .then(resp => resp.json())
  .then((item) => resolve(item))
  .catch(e => console.error('Something failed!', e)

另外,使用new Promisein没有任何意义getCustomer,只是return来自的承诺fetch

function getCustomer(customer_id) {
  const url = 'http://127.0.0.1:8000/customer-detail/' + customer_id+ '/';
  return fetch(url)
    .then(resp => resp.json())
    .then((item) => resolve(item))
    .catch(e => console.error('Something failed!', e));
}

但总的来说,我建议您查看async/ await,它会极大地清理您的代码,并使您自己更容易阅读和理解:

async function test (pmt_id, crm_supplier_id) {
  try {
    const url = `http://127.0.0.1:8000/creditor-detail/${encodeURIComponent(pmt_id)}/supplier/${encodeURIComponent(crm_supplier_id}/`
    const listResponse = await fetch(url)
    if (listResponse.status !== 200) throw new Error(`List request failed with status ${indexResponse.status}`)
    const listResult = await listResponse.json()
  
    const results = await Promise.all(listResult.map(c => getCustomer(c.customer_id)))
  
    console.log('All done', results)
  } catch (err) {
    console.log(err)
  }
}

async function getCustomer (customer_id) {
  const customerResponse = await fetch(`http://127.0.0.1:8000/customer-detail/${encodeURIComponent(customer_id)}/`)
  if (customerResponse.status !== 200) throw new Error(`Customer request failed with status ${customerResponse.status}`)
  const customerResult = await customerResponse.json()
  return customerResult
}
于 2020-07-30T20:15:50.700 回答