问题
A really simply question. I've boiled it down to the simplest version that illustrates my problem.
Why does this vanilla JS return a promise, and how can I get it to return "Hello"?
let result = test()
.then(function(result) {
return result;
});
alert(result);
function test(serialized) {
return new Promise(function(resolve, reject) {
resolve("Hello");
});
}
回答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");
});
}
回答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))
来源:https://stackoverflow.com/questions/56134951/why-does-this-simple-js-promise-return-a-promise