I need help with JavaScript Promises

Hello there,
I am having a hard time getting something to work and I am hoping there is someone here who can point me into the right direction.
I basically have two functions. Let’s say function A and function B. Function B contains a chained Promise and returns a Promise that function A processes and produces an outcome. Here is my code:

function A {
    B().
        then(function(data) {
			// This is empty, and is not called. Not sure why??
			console.log(data);
        });
}

function B {
	var promise_1 = function() {
		return new Promise(function(resolve, reject) {
			// Ajax call here
			resolve(data);
		});
	}
	
	var promise_2 = function(data) {
		return new Promise(function(resolve, reject) {
			// Another Ajax call here that depends on the data returned by Promise 1 above
			resolve(data);
		});
	}
	
	return promise_1
		.then(function(data) {
			return promise_2(data);
		})
}

I hope the code makes sense. Please let me know what I am doing wrong. I thank you!

Hi, promise_1 returns a Promise, but it never gets called; try

return promise_1().then(/* ... */)

instead. But this wrapping factory function is actually not even necessary (not in your example code at any rate); also note that .then() always returns a Promise anyway, so the second Promise is a bit redundant. You might condense it to something like

function a () {
  b().then(data => {
    console.log(data)
  })
}

function b () {
  const myPromise = new Promise((resolve, reject) => {
    // Do AJAX call
    resolve(data)
  })

  return myPromise.then(data => {
    // Do more AJAX, then simply resolve like
    return moreData

    // Or reject like
    throw reason
  })
}

jsbin

PS: There are the parentheses missing in your function declarations… but I suppose your question was not about syntax errors. ^^

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.