javascriptnode.jsrequest-promise

Proper way to send post request using Promise


I dont know if I am properly using the promise, the problem here is that sending request is too long.

This is my current code

exports.updatePostApi = async (datas) => {
  return new Promise(async (resolve, reject) => {
    setTimeout(async () => {
      let api = "user/update?_method=PUT";
      let data = new FormData();
      let result = {};
      data.append("userbody", JSON.stringify(datas));
      console.log(data._valueLength + data._overheadLength + 56, "length");
      const config = {
        method: "post",
        baseURL: apiEndpoint,
        url: api,
        data: data,
        headers: {
          "BIR-Authorization": Authorization,
          "Content-Type": `multipart/form-data; boundary=${data._boundary}`,
          "Content-Length": data._valueLength + data._overheadLength + 56,
        },
        maxBodyLength: Infinity,
        maxContentLength: Infinity,
      };

      return await axios(config);

      console.log(result);
      resolve(result);
    }, 5000);
  });

};

Solution

  • I shortened your code and return the promise of axios so one can result = await updatePostApi(data)

    exports.updatePostApi = async (datas) => {
          await new Promise(resolve => setTimeout(resolve, 5000))
    
          let data = new FormData();
          data.append("userbody", JSON.stringify(datas));
          
          return axios({
            method: "post",
            baseURL: apiEndpoint,
            url: "user/update?_method=PUT",
            data: data,
            headers: {
              "BIR-Authorization": Authorization,
              "Content-Type": `multipart/form-data; boundary=${data._boundary}`,
              "Content-Length": data._valueLength + data._overheadLength + 56,
            },
            maxBodyLength: Infinity,
            maxContentLength: Infinity,
          });
    };