【问题标题】:Axios function call won't return dataaxios函数调用不会返回数据
【发布时间】:2021-11-17 14:45:51
【问题描述】:

我确定这是我的理解/实施的问题。问题是我试图将创建的对象的 ID 返回到一个数组中,以便以后可以将数组插入到另一个对象中。在函数、调用之间移动 .then() 似乎没有任何效果。推送到数组,通过索引将值分配给数组似乎不起作用。任何有关根本问题是什么以及解决问题的途径的见解/指导都将受到赞赏。

index.js

const contacts = document.getElementsByName('newContact');
const contactName = document.getElementsByName('contactName');
const contactTitle = document.getElementsByName('contactTitle');
const contactPhone = document.getElementsByName('contactPhone');
const contactEmail = document.getElementsByName('contactEmail');
let contactIDArray = new Array();
for (let i = 0; i < contacts.length; i++) {
  const name = contactName[i].value;
  const title = contactTitle[i].value;
  const phone = contactPhone[i].value;
  const email = contactEmail[i].value;
  var id;
  createContact(name, title, phone, email).then(function (res) {
    id = res.data.id;
    alert(res.data.id);
    return id;
  });
  alert(id);

contact.js

import axios from 'axios';

export const createContact = async (contactName, contactTitle, contactPhone, contactEmail) => {
  try {
    const res = await axios({
      method: 'POST',
      url: '/api/v1/contacts',
      data: {
        contactName,
        contactTitle,
        contactPhone,
        contactEmail,
      },
    });
    return res.data.id;
  } catch (err) {
    console.log(err);
  }
};

【问题讨论】:

  • createContact 返回res.data.id,然后您尝试再次从中获取.data.id
  • 我不确定你想用循环实现什么:id 将在每个回调调用中重新分配。此外,您的回调正在返回 id,但之后您没有使用它
  • @jkoestinger 该循环将负责在后端创建一个或多个联系人文档。联系人属于另一个称为标签的结构。该数组用于将每个联系人字段的 ID 附加到标签。我可以将联系人存储在标签本身中,但这会破坏我们存储的联系人共享功能。
  • @KrzysztofKrzeszewski 我正在调查,谢谢!

标签: javascript async-await axios


【解决方案1】:

I'm trying to return the ID of the created object into an array so that array can later be inserted into another object

根据您的要求,我有几件事要给您:

  1. 就像 jkoestinger 的回答一样,除非您确实需要,否则不要在循环中使用 async/await 或异步函数 (.then())。
  2. 不要直接从异步调用返回属性,您应该返回整个对象并获取 ID。这是一个很好的做法。

请看下面修改后的代码:

index.js

let contactPromises = [];

for (let i = 0; i < contacts.length; i++) {
  const name = contactName[i].value;
  const title = contactTitle[i].value;
  const phone = contactPhone[i].value;
  const email = contactEmail[i].value;
  
  contactPromises.push(createContact(name, title, phone, email));
}

let contacts = (contactPromises.length > 0) ? await Promise.all(contactPromises) : [];
let contactIds = contacts.map(contact => contact.id);
// use your contactIds here

axios

let res = await axios({
  method: 'POST',
  url: '/api/v1/contacts',
  data: {
    contactName,
    contactTitle,
    contactPhone,
    contactEmail,
  },
});

return res.data;   // <--- return res.data only, not the res.data.id

【讨论】:

    【解决方案2】:

    我可以看到多个问题:

    1. 正如 VLAZ 在评论中指出的那样,您正在尝试在已经是 id 的值上获取 .data.id
    2. 应使用Promise util 提供的工具来创建一系列promise(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all 可能是您正在寻找的工具)。

    例如,我会按照这些思路去做(未经测试):

    const contacts = document.getElementsByName('newContact');
    const contactName = document.getElementsByName('contactName');
    const contactTitle = document.getElementsByName('contactTitle');
    const contactPhone = document.getElementsByName('contactPhone');
    const contactEmail = document.getElementsByName('contactEmail');
    let contactIDArray = new Array();
    
    const requests = []
    
    for (let i = 0; i < contacts.length; i++) {
      const name = contactName[i].value;
      const title = contactTitle[i].value;
      const phone = contactPhone[i].value;
      const email = contactEmail[i].value;
      var id;
      promise = createContact(name, title, phone, email).then(function (res) {
        const id = res.data.id;
        alert(res.data.id);
        return id;
      });
      requests.push(promise)
    } 
    
    Promise.all(requests).then(ids => {
        // This should contain the array of ids
        alert(ids)
    })
    
    

    编辑: 此外,请注意在同步和异步调用之间共享结果,通常一旦您开始异步任务,您就会留在异步世界中,如下所述:How to return data from promise

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 2020-11-10
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多