Using promise to GET over XHR returns pending promise












0















I'm trying to use promises to make asynchronous requests over XHR. I can console.log my result from within .then, but outside it returns pending.



function initRequest(url) {
return new Promise(function(resolve, reject) {
xhr.open("GET", url, true);
xhr.onload = function(e) {
// check if XHR transaction is complete
if (xhr.readyState === 4) {
// if it is, do the things
if (xhr.status === 200) {
// Parse outfitList
responseText = JSON.parse(xhr.response)
resolve(this.responseText);
// Print outfitList to cards
var div = document.getElementById('outfitCards');
//return outfitList;

// If it can't, do an error
} else {
console.error(xhr.statusText);
}
}
};
xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
xhr.send();
});
}

var newResult = initRequest('/outfits/outfitList')
.then(function(result) {
console.log(result)
resolve(result);
})
.catch(function() {
console.log('err')
});

console.log(newResult);


result is an array, which looks fine when I console.log(result). console.log(newResult) however, returns a pending promise.










share|improve this question





























    0















    I'm trying to use promises to make asynchronous requests over XHR. I can console.log my result from within .then, but outside it returns pending.



    function initRequest(url) {
    return new Promise(function(resolve, reject) {
    xhr.open("GET", url, true);
    xhr.onload = function(e) {
    // check if XHR transaction is complete
    if (xhr.readyState === 4) {
    // if it is, do the things
    if (xhr.status === 200) {
    // Parse outfitList
    responseText = JSON.parse(xhr.response)
    resolve(this.responseText);
    // Print outfitList to cards
    var div = document.getElementById('outfitCards');
    //return outfitList;

    // If it can't, do an error
    } else {
    console.error(xhr.statusText);
    }
    }
    };
    xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
    xhr.send();
    });
    }

    var newResult = initRequest('/outfits/outfitList')
    .then(function(result) {
    console.log(result)
    resolve(result);
    })
    .catch(function() {
    console.log('err')
    });

    console.log(newResult);


    result is an array, which looks fine when I console.log(result). console.log(newResult) however, returns a pending promise.










    share|improve this question



























      0












      0








      0


      1






      I'm trying to use promises to make asynchronous requests over XHR. I can console.log my result from within .then, but outside it returns pending.



      function initRequest(url) {
      return new Promise(function(resolve, reject) {
      xhr.open("GET", url, true);
      xhr.onload = function(e) {
      // check if XHR transaction is complete
      if (xhr.readyState === 4) {
      // if it is, do the things
      if (xhr.status === 200) {
      // Parse outfitList
      responseText = JSON.parse(xhr.response)
      resolve(this.responseText);
      // Print outfitList to cards
      var div = document.getElementById('outfitCards');
      //return outfitList;

      // If it can't, do an error
      } else {
      console.error(xhr.statusText);
      }
      }
      };
      xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
      xhr.send();
      });
      }

      var newResult = initRequest('/outfits/outfitList')
      .then(function(result) {
      console.log(result)
      resolve(result);
      })
      .catch(function() {
      console.log('err')
      });

      console.log(newResult);


      result is an array, which looks fine when I console.log(result). console.log(newResult) however, returns a pending promise.










      share|improve this question
















      I'm trying to use promises to make asynchronous requests over XHR. I can console.log my result from within .then, but outside it returns pending.



      function initRequest(url) {
      return new Promise(function(resolve, reject) {
      xhr.open("GET", url, true);
      xhr.onload = function(e) {
      // check if XHR transaction is complete
      if (xhr.readyState === 4) {
      // if it is, do the things
      if (xhr.status === 200) {
      // Parse outfitList
      responseText = JSON.parse(xhr.response)
      resolve(this.responseText);
      // Print outfitList to cards
      var div = document.getElementById('outfitCards');
      //return outfitList;

      // If it can't, do an error
      } else {
      console.error(xhr.statusText);
      }
      }
      };
      xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
      xhr.send();
      });
      }

      var newResult = initRequest('/outfits/outfitList')
      .then(function(result) {
      console.log(result)
      resolve(result);
      })
      .catch(function() {
      console.log('err')
      });

      console.log(newResult);


      result is an array, which looks fine when I console.log(result). console.log(newResult) however, returns a pending promise.







      javascript node.js promise xmlhttprequest






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 31 '18 at 13:38









      JO3-W3B-D3V

      1,487420




      1,487420










      asked Dec 31 '18 at 12:42









      owiewioowiewio

      64




      64
























          2 Answers
          2






          active

          oldest

          votes


















          1














          This is also the expected behavior.
          Have you understood how asynchronous code behaves?



          The console.log(newResult) is run before this:



          var newResult = initRequest('/outfits/outfitList')
          .then(function (result) {
          console.log(result)
          resolve(result);
          })
          .catch(function () {
          console.log('err')
          });


          You should do work with your results inside the.then() callback:



            var newResult = initRequest('/outfits/outfitList')
          .then(function (result) {
          // Do your stuff with results here

          })
          .catch(function () {
          console.log('err')
          });


          If you think is is hard to read, you can try to use async/await instead



          var result = await initRequest('/outfits/outfitList')
          console.log(result)





          share|improve this answer































            0














            I think your code is missing the reject state, maybe your request wasn't completed as you expected. Try this improved code:



            function initRequest(url) {
            return new Promise(function (resolve, reject) {
            xhr.open("GET", url, true);
            xhr.onload = function (e) {
            // check if XHR transaction is complete
            if (xhr.readyState === 4) {
            // if it is, do the things
            if (xhr.status === 200) {
            // Parse outfitList
            responseText = JSON.parse(xhr.response)
            resolve(this.responseText);
            // Print outfitList to cards
            var div = document.getElementById('outfitCards');
            //return outfitList;

            // If it can't, do an error
            }
            else {
            console.error(xhr.statusText);
            reject(xhr.statusText);
            }
            } else {
            reject(xhr.statusText);
            }
            };
            xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
            xhr.send();
            });
            }


            And:



            var newResult = initRequest('/outfits/outfitList')
            .then(function (result) {
            console.log(result)
            resolve(result);
            })
            .catch(function () {
            console.log('err');
            reject('error in request');
            });





            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53987666%2fusing-promise-to-get-over-xhr-returns-pending-promise%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              This is also the expected behavior.
              Have you understood how asynchronous code behaves?



              The console.log(newResult) is run before this:



              var newResult = initRequest('/outfits/outfitList')
              .then(function (result) {
              console.log(result)
              resolve(result);
              })
              .catch(function () {
              console.log('err')
              });


              You should do work with your results inside the.then() callback:



                var newResult = initRequest('/outfits/outfitList')
              .then(function (result) {
              // Do your stuff with results here

              })
              .catch(function () {
              console.log('err')
              });


              If you think is is hard to read, you can try to use async/await instead



              var result = await initRequest('/outfits/outfitList')
              console.log(result)





              share|improve this answer




























                1














                This is also the expected behavior.
                Have you understood how asynchronous code behaves?



                The console.log(newResult) is run before this:



                var newResult = initRequest('/outfits/outfitList')
                .then(function (result) {
                console.log(result)
                resolve(result);
                })
                .catch(function () {
                console.log('err')
                });


                You should do work with your results inside the.then() callback:



                  var newResult = initRequest('/outfits/outfitList')
                .then(function (result) {
                // Do your stuff with results here

                })
                .catch(function () {
                console.log('err')
                });


                If you think is is hard to read, you can try to use async/await instead



                var result = await initRequest('/outfits/outfitList')
                console.log(result)





                share|improve this answer


























                  1












                  1








                  1







                  This is also the expected behavior.
                  Have you understood how asynchronous code behaves?



                  The console.log(newResult) is run before this:



                  var newResult = initRequest('/outfits/outfitList')
                  .then(function (result) {
                  console.log(result)
                  resolve(result);
                  })
                  .catch(function () {
                  console.log('err')
                  });


                  You should do work with your results inside the.then() callback:



                    var newResult = initRequest('/outfits/outfitList')
                  .then(function (result) {
                  // Do your stuff with results here

                  })
                  .catch(function () {
                  console.log('err')
                  });


                  If you think is is hard to read, you can try to use async/await instead



                  var result = await initRequest('/outfits/outfitList')
                  console.log(result)





                  share|improve this answer













                  This is also the expected behavior.
                  Have you understood how asynchronous code behaves?



                  The console.log(newResult) is run before this:



                  var newResult = initRequest('/outfits/outfitList')
                  .then(function (result) {
                  console.log(result)
                  resolve(result);
                  })
                  .catch(function () {
                  console.log('err')
                  });


                  You should do work with your results inside the.then() callback:



                    var newResult = initRequest('/outfits/outfitList')
                  .then(function (result) {
                  // Do your stuff with results here

                  })
                  .catch(function () {
                  console.log('err')
                  });


                  If you think is is hard to read, you can try to use async/await instead



                  var result = await initRequest('/outfits/outfitList')
                  console.log(result)






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 31 '18 at 12:50









                  RoiRoi

                  494111




                  494111

























                      0














                      I think your code is missing the reject state, maybe your request wasn't completed as you expected. Try this improved code:



                      function initRequest(url) {
                      return new Promise(function (resolve, reject) {
                      xhr.open("GET", url, true);
                      xhr.onload = function (e) {
                      // check if XHR transaction is complete
                      if (xhr.readyState === 4) {
                      // if it is, do the things
                      if (xhr.status === 200) {
                      // Parse outfitList
                      responseText = JSON.parse(xhr.response)
                      resolve(this.responseText);
                      // Print outfitList to cards
                      var div = document.getElementById('outfitCards');
                      //return outfitList;

                      // If it can't, do an error
                      }
                      else {
                      console.error(xhr.statusText);
                      reject(xhr.statusText);
                      }
                      } else {
                      reject(xhr.statusText);
                      }
                      };
                      xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
                      xhr.send();
                      });
                      }


                      And:



                      var newResult = initRequest('/outfits/outfitList')
                      .then(function (result) {
                      console.log(result)
                      resolve(result);
                      })
                      .catch(function () {
                      console.log('err');
                      reject('error in request');
                      });





                      share|improve this answer




























                        0














                        I think your code is missing the reject state, maybe your request wasn't completed as you expected. Try this improved code:



                        function initRequest(url) {
                        return new Promise(function (resolve, reject) {
                        xhr.open("GET", url, true);
                        xhr.onload = function (e) {
                        // check if XHR transaction is complete
                        if (xhr.readyState === 4) {
                        // if it is, do the things
                        if (xhr.status === 200) {
                        // Parse outfitList
                        responseText = JSON.parse(xhr.response)
                        resolve(this.responseText);
                        // Print outfitList to cards
                        var div = document.getElementById('outfitCards');
                        //return outfitList;

                        // If it can't, do an error
                        }
                        else {
                        console.error(xhr.statusText);
                        reject(xhr.statusText);
                        }
                        } else {
                        reject(xhr.statusText);
                        }
                        };
                        xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
                        xhr.send();
                        });
                        }


                        And:



                        var newResult = initRequest('/outfits/outfitList')
                        .then(function (result) {
                        console.log(result)
                        resolve(result);
                        })
                        .catch(function () {
                        console.log('err');
                        reject('error in request');
                        });





                        share|improve this answer


























                          0












                          0








                          0







                          I think your code is missing the reject state, maybe your request wasn't completed as you expected. Try this improved code:



                          function initRequest(url) {
                          return new Promise(function (resolve, reject) {
                          xhr.open("GET", url, true);
                          xhr.onload = function (e) {
                          // check if XHR transaction is complete
                          if (xhr.readyState === 4) {
                          // if it is, do the things
                          if (xhr.status === 200) {
                          // Parse outfitList
                          responseText = JSON.parse(xhr.response)
                          resolve(this.responseText);
                          // Print outfitList to cards
                          var div = document.getElementById('outfitCards');
                          //return outfitList;

                          // If it can't, do an error
                          }
                          else {
                          console.error(xhr.statusText);
                          reject(xhr.statusText);
                          }
                          } else {
                          reject(xhr.statusText);
                          }
                          };
                          xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
                          xhr.send();
                          });
                          }


                          And:



                          var newResult = initRequest('/outfits/outfitList')
                          .then(function (result) {
                          console.log(result)
                          resolve(result);
                          })
                          .catch(function () {
                          console.log('err');
                          reject('error in request');
                          });





                          share|improve this answer













                          I think your code is missing the reject state, maybe your request wasn't completed as you expected. Try this improved code:



                          function initRequest(url) {
                          return new Promise(function (resolve, reject) {
                          xhr.open("GET", url, true);
                          xhr.onload = function (e) {
                          // check if XHR transaction is complete
                          if (xhr.readyState === 4) {
                          // if it is, do the things
                          if (xhr.status === 200) {
                          // Parse outfitList
                          responseText = JSON.parse(xhr.response)
                          resolve(this.responseText);
                          // Print outfitList to cards
                          var div = document.getElementById('outfitCards');
                          //return outfitList;

                          // If it can't, do an error
                          }
                          else {
                          console.error(xhr.statusText);
                          reject(xhr.statusText);
                          }
                          } else {
                          reject(xhr.statusText);
                          }
                          };
                          xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
                          xhr.send();
                          });
                          }


                          And:



                          var newResult = initRequest('/outfits/outfitList')
                          .then(function (result) {
                          console.log(result)
                          resolve(result);
                          })
                          .catch(function () {
                          console.log('err');
                          reject('error in request');
                          });






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Dec 31 '18 at 12:59









                          abd0991abd0991

                          2418




                          2418






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53987666%2fusing-promise-to-get-over-xhr-returns-pending-promise%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Mossoró

                              Error while reading .h5 file using the rhdf5 package in R

                              Pushsharp Apns notification error: 'InvalidToken'