Why Does This Simple JS Promise Return A Promise?
Solution 1:
What's happening is that you are "alerting" the value returned by the then
method.
The then
method will always return a promise, even if you are returning a value, it's wrapped in a resolved promise (e.g. Promise.resolve('Hello')
), this allows you to achieve chainability, for instance you can call and return other promises in the then
callback, and they will wait the resolution to continue and resolve.
test()
.then(function(result) {
console.log(result);
return result + ' world!';
}).then(function(result2) {
console.log(result2); // Hello world!
return new Promise(function (resolve) { resolve('End') });
}).then(function (result) {
console.log(result);
})
function test(serialized) {
return new Promise(function(resolve, reject) {
resolve("Hello");
});
}
Solution 2:
promise.then((result) => {})
always return another promise, so that we can chain multiple .then()
calls.
how can I get it to return "Hello"?
: For this you must await
a promise.
for eg: alert(await test())
problem is that you can use await only within an async function.
Another option is to alert within then.
test().then((result) => alert(result))
Post a Comment for "Why Does This Simple JS Promise Return A Promise?"