Return from a Promise Then()

JS: what happens if to return a new Promise inside a callback of a then-statement

Promise.prototype.then()

The then() method returns a
Promise.
It takes up to two arguments: callback functions for the success and
failure cases of the Promise.

...

Return value

Once a Promise is fulfilled or rejected, the respective handler
function (onFulfilled or onRejected) will be called asynchronously
(scheduled in the current thread loop). The behavior of the handler
function follows a specific set of rules. If a handler function:

  • returns a value, the promise returned by then gets resolved with the returned value as its value.
  • doesn't return anything, the promise returned by then gets resolved with an undefined value.
  • throws an error, the promise returned by then gets rejected with the thrown error as its value.
  • returns an already fulfilled promise, the promise returned by then gets fulfilled with that promise's value as its value.
  • returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
  • returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the
    resolution/rejection of the promise returned by the handler. Also, the
    resolved value of the promise returned by then will be the same as
    the resolved value of the promise returned by the handler.

Source: MDN

The last (bold) bullet point is the answer to your question

Does the then() function return a promise reflecting the results of the previous promise?

Thanks for replies and I have already selected the answer. Based on the input given by you people this is what I have understood further.

sql.connect(config).then(function(connection) {
return connection.request().query('select * from Users')
})

In the code given above, sql.connect part is using an SQL module to call a connect() method which is supposed to return a promise (in case of failure returns an error else a connection object). On connect() we call a then() method which takes a callback function function(connection) to get registered so that can be called later at the point where connect returns a promise (in case of success i.e. connection object) and later

.then(function(result) {
console.dir(result);
res.send(result);
}).

is called on the promise returned by .query('select * from Users') part of the previous .then() method's callback function and so on.

returning a promise from the then of another promise

I think it's as simple as adding a return before new Promise... in line 12. Revised code:

function topLevel() {
level2()
.then(() => {
console.log("topLevel resolved")
})
}

let testError = true;

function level2() {
if(testError) {
// Added "return" here
return new Promise((resolve, reject) => {
resolve("Level 2");
})
.then(() => {
return (level3());
})
}
else {
return (level3());
}
}

function level3() {
return (new Promise((resolve, reject) => {
resolve("Level 3");
}));
}

promise.then() returns Promise { pending }

Reduced your code by a bit instead of adding multiple promise resolution

  const fetch = require('node-fetch');

const everything = async () =>{
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const {id} = await response.json();
return `https://cdn.test.com/${id}`
}
everything().then((res)=>console.log(res));

Javascript, Promise.then return values

It is the behaviour of a promise, it is described here

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

In Return value section:

if the handler function returns a value, the promise returned by then
gets resolved with the returned value as its value;

Using promise .then return promise and wrap previous response

In console.log(res) you want to print the value returned by sleep.then(...) inside the main() function. However, that function is not returning that value. In fact, it isn't returning anything, so res is undefined.

Inside main(), you should return sleep.then(...). That way, res will be the value which is returned by that promise.

function sleep(input, timeout) {
return new Promise(resolve => {
setTimeout(resolve(input), timeout)});
}

async function main() {
return sleep(['a','b'],1000)
.then(([first, second]) => {
console.log(first)
console.log(second);
return [first+'t', second];
});
}
main()
.then(res => {
console.log(res);
})


Related Topics



Leave a reply



Submit