一个非常简单的问题.我已经把它归结为最简单的版本来说明我的问题.
为什么这个vanilla JS会返回一个promise,我怎样才能让它返回Hello"?
让结果 = 测试().then(函数(结果){返回结果;});警报(结果);功能测试(序列化){返回新的承诺(功能(解决,拒绝){解决(你好");});} 解决方案发生的事情是您正在警告"then 方法返回的值.
then 方法总是会返回一个 promise,即使你返回的是一个值,它也会被封装在一个已解析的 promise 中(例如 Promise.resolve('Hello')),这样你就可以实现chainability,比如你可以在then回调中调用和返回其他promise,它们会等待解析继续并解析.>
test().then(函数(结果){控制台日志(结果);返回结果+'世界!';}).那么(函数(结果2){控制台日志(结果2);//你好,世界!return new Promise(function (resolve) { resolve('End') });}).then(函数(结果){控制台日志(结果);})功能测试(序列化){返回新的承诺(功能(解决,拒绝){解决(你好");});}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"); }); }
解决方案
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"); }); }
更多推荐
为什么这个简单的 JS 承诺会返回一个承诺?
发布评论