How can I get the right response promise?

Active3 hr before
Viewed126 times

8 Answers


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) {
         video: true,
         audio: true
      .then(chatStream => {
         selfViewElem.srcObject = chatStream;
         chatStream.getTracks().forEach(track => myPeerConnection.addTrack(track, chatStream));
      }).catch(err => {
         setStatusMessage("Failed to connect");
load more v

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();"GET", URL);
      req.onload = function() {
         if (req.status == 200) {
         } else {
            reject("There is an Error!");
   return promise;

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'
   } else {
      const why = 'Still working on something else'
load more v

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 =;
            console.log(theParentId); // #1

Use resolve in router method:

resolve: {
   parentId: function(your_factory) {

Use run method of app to resolve your service. {
load more v

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

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

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

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?"