How can I get the right response promise?

Asked
Active3 hr before
Viewed126 times

8 Answers

rightpromiseresponse
90%

The trouble with callbacks,Bear in mind that the value returned by a fulfilled promise becomes the parameter passed to the next .then() block's callback function.,When the promise is fulfilled, the values passed into the fulfillment handler would contain three Response objects, one for each of the fetch() operations that have completed.

function handleCallButton(evt) {
   setStatusMessage("Calling...");
   navigator.mediaDevices.getUserMedia({
         video: true,
         audio: true
      })
      .then(chatStream => {
         selfViewElem.srcObject = chatStream;
         chatStream.getTracks().forEach(track => myPeerConnection.addTrack(track, chatStream));
         setStatusMessage("Connected");
      }).catch(err => {
         setStatusMessage("Failed to connect");
      });
}
load more v
88%

So how do we code this using callback functions? I came up with something like this:,Oh, yes! That's right. We have callback functions in JavaScript. But, a callback is not a special thing in JavaScript. It is a regular function that produces results after an asynchronous call completes (with success/error).,JavaScript undefined and null: Let's talk about it one last time!

function getPromise(URL) {
   let promise = new Promise(function(resolve, reject) {
      let req = new XMLHttpRequest();
      req.open("GET", URL);
      req.onload = function() {
         if (req.status == 200) {
            resolve(req.response);
         } else {
            reject("There is an Error!");
         }
      };
      req.send();
   });
   return promise;
}
72%

It's unlikely that in modern JavaScript you'll find yourself not using promises, so let's start diving right into them.,If you get the Uncaught TypeError: undefined is not a promise error in the console, make sure you use new Promise() instead of just Promise(),The created promise will eventually end in a resolved state, or in a rejected state, calling the respective callback functions (passed to then and catch) upon finishing.

The Promise API exposes a Promise constructor, which you initialize using new Promise():

JScopylet done = true
const isItDoneYet = new Promise((resolve, reject) => {
   if (done) {
      const workDone = 'Here is the thing I built'
      resolve(workDone)
   } else {
      const why = 'Still working on something else'
      reject(why)
   }
})
load more v
65%

3 No - you cannot - any operations you want to do with response must go in the .then() handler. You can't write asynchronous Javascript in a synchronous style! – slugonamission May 30 '16 at 21:43 ,Connect and share knowledge within a single location that is structured and easy to search., Can I avoid informal personal interactions at companies that offer free lunch?

Firstly, write result to a property of your service:

app.factory('your_factory', function() {
   var theParentIdResult = null;
   var factoryReturn = {
      theParentId: theParentIdResult,
      addSiteParentId: addSiteParentId
   };
   return factoryReturn;

   function addSiteParentId(nodeId) {
      var theParentId = 'a';
      var parentId = relationsManagerResource.GetParentId(nodeId)
         .then(function(response) {
            factoryReturn.theParentIdResult = response.data;
            console.log(theParentId); // #1
         });
   }
})

Use resolve in router method:

resolve: {
   parentId: function(your_factory) {
      your_factory.addSiteParentId();
   }
}

Use run method of app to resolve your service.

app.run(function(your_factory) {
   your_factory.addSiteParentId();
})
load more v
75%

You punch the air! About time right? You've used these Promise things before but it bothers you that all implementations have a slightly different API. What's the API for the official JavaScript version? You probably want to begin with the terminology.,Although promise implementations follow a standardized behaviour, their overall APIs differ. JavaScript promises are similar in API to RSVP.js. Here's how you create a promise:,In this trivial example, all of the chapters arrive around the same time, but the benefit of displaying one at a time will be exaggerated with more, larger chapters.

var img1 = document.querySelector('.img-1');
img1.addEventListener('load', function() { // woo yey image loaded});img1.addEventListener('error', function() {  // argh everything's broken});
load more v
40%

This can potentially take a long time, and we do not want to freeze the thread while we wait for the response. Instead, we'll create a callback that will be notified when the response comes in.,Instead of returning concrete values, these asynchronous functions return a Promise object, which will at some point either be fulfilled or not.,Until that time, the rest of the code is being executed, like presenting posts and notifications.

If you are a JavaScript developer, you've likely heard of, if not used, callbacks:

function hello() {
   console.log('Hello World!');
}

setTimeout(hello, 5000);
load more v
22%

This makes a network request to the url and returns a promise. The promise resolves with a response object when the remote server responds with headers, but before the full response is downloaded.,To read the full response, we should call the method response.text(): it returns a promise that resolves when the full text is downloaded from the remote server, with that text as a result.,The response object returned from fetch also includes the method response.json() that reads the remote data and parses it as JSON. In our case that’s even more convenient, so let’s switch to it.

new Promise(function(resolve, reject) {

   setTimeout(() => resolve(1), 1000); // (*)

}).then(function(result) { // (**)

   alert(result); // 1
   return result * 2;

}).then(function(result) { // (***)

   alert(result); // 2
   return result * 2;

}).then(function(result) {

   alert(result); // 4
   return result * 2;

});
load more v
60%

4.1.1 Promise-returning functions must always return promises ,4.1.1. Promise-returning functions must always return promises ,User interface prompts: methods that ask the user for an answer could return a promise.

function addDelay(promise, ms) {
   return Promise.resolve(promise).then(v =>
      new Promise(resolve =>
         setTimeout(() => resolve(v), ms);
      )
   );
}

var p1 = addDelay(doAsyncOperation(), 500);
var p2 = addDelay("value", 1000);

Other "right-promise" queries related to "How can I get the right response promise?"